How to create an image gallery with HTML

From the HTML perspective, an image gallery is a web page consisting of a section containing multiple images organized in a specific format. Its purpose is to showcase a collection of photographs, product images, artwork, etc.

Coding example

Below is an example of creating an image gallery vias HTML. To make it a bit more interactive, CSS and JavaScript is also added.

Create an image gallery

Explanation

Here’s given the explanation of all the files being added in the code above:

The HTML file

  • Lines 12–19:
    • We create an image gallery using a <div> element with class name of image_gallery.
    • It contains 66 <img> tags, each of them loading randomly generated images from the lorem picsum website.
  • Lines 21–24:
    • We create a container for displaying a single image using <div> element of id of expanded_img.
    • This container also contains a <span> element with a class name of close; this is used to create a close button. Finally, an <img> tag with a class name of img_content and id of image; this is to display the image.

The CSS file

  • This file contains the CSS for styling purposes in order to give the web page a good aesthetic.

The JavaScript file

  • Lines 1–6:

    • The function, showImage, takes one argument—src as the image source.
    • Furthermore, it gets elements by their id via document.getElementById() method, which are:
      • expanded_img
      • images
    • We set the style to block.
    • We set the image source, i.e., src to src as the argument passed in the showImage function.
  • Lines 8–11

    • The function closeImage gets the element expanded_img by id via document.getElementById() method.
    • We set the style of this element’s display property to none.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved