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.
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 withclassname ofimage_gallery. - It contains
<img>tags, each of them loading randomly generated images from the lorem picsum website.
- We create an image gallery using a
- Lines 21–24:
- We create a container for displaying a single image using
<div>element ofidofexpanded_img. - This container also contains a
<span>element with aclassname ofclose; this is used to create a close button. Finally, an<img>tag with aclassname ofimg_contentandidofimage; this is to display the image.
- We create a container for displaying a single image using
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—srcas the image source. - Furthermore, it gets elements by their
idviadocument.getElementById()method, which are:expanded_imgimages
- We set the style to
block. - We set the image source, i.e.,
srctosrcas the argument passed in theshowImagefunction.
- The function,
-
Lines 8–11
- The function
closeImagegets the elementexpanded_imgbyidviadocument.getElementById()method. - We set the style of this element’s
displayproperty tonone.
- The function
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved