How to make a simple gallery with CSS and 6 lines of JavaScript?

- 👤 Andrés Cruz

🇪🇸 En español

How to make a simple gallery with CSS and 6 lines of JavaScript?

See examples Download source

Creating an image gallery with JavaScript doesn't have to involve heavy libraries, complex animations, or dozens of lines of code. After several experiments with responsive galleries, I reached a clear conclusion: CSS can do most of the work, and JavaScript should only act as a trigger.

In this article, I show you how to build a functional, responsive, and maintainable gallery using HTML + CSS and just six lines of JavaScript, achieving an "open image" effect upon clicking:

Although much of the CSS and HTML code is the same as used in previous experiments, new modifications have been incorporated, such as the addition of six (6) lines of JavaScript to create an "open an image" effect when selecting it.

What we are going to build and why use minimal JavaScript

The idea is simple:

  • Display several images in a gallery format.
  • When clicking on an image, it "opens" and occupies the center of the screen.
  • When clicking again, the image returns to its original state.

In my previous tests with galleries, I found that moving elements, calculating positions, or animating from JavaScript only added unnecessary complexity. Instead, by delegating the visual behavior to CSS and limiting JavaScript to adding or removing a class, the code becomes cleaner and easier to maintain.

HTML structure of the gallery

We define the basic structure that the gallery will have; in other words, the HTML:

<div id="container">
  <div onclick="galery(this)">
    <img src="img/arya-stark.jpg" />
    <span>Arya Stark</span>
  </div>
  ***
  <div onclick="galery(this)">
    <img src="img/jon-snow.jpg" />
    <span>Jon Snow</span>
  </div>
</div>

If you have read some of the previous posts on how to create a gallery, you will notice that the HTML structure has not changed at all except for the addition of the onclick attribute that invokes the JavaScript function we will see below.

Images and description

Each image includes an <img> and a <span> for the description. I had already used this structure in previous experiments, and it worked well without the need for major changes.

Using the onclick event to activate the gallery

The only difference compared to a purely CSS gallery is the use of the onclick attribute, which invokes a JavaScript function when an image is selected.

JavaScript: opening an image with just 6 lines

As mentioned in the title and introduction of this post: with only 6 lines we can create the effect where, upon selecting an image, it "opens" or, in other words, occupies the center of the screen in a larger proportion; essentially, the JavaScript adds and removes a class called select which centers the image in the middle of the screen:

function galery(e){
  if(e.classList.length == 0)
    e.classList.add("select")
  else
    e.classList.remove("select")
}

Why JavaScript only adds and removes classes

  • The JavaScript is limited to:
    • Detecting the click.
    • Adding or removing the "select" class.
  • This approach is ideal because:
    • It reduces errors.
    • It improves code readability.
    • It facilitates future visual modifications without touching JS.
  • Advantages over more complex solutions. Unlike galleries based on plugins or libraries:
    • You don't depend on third parties.
    • You don't load unnecessary JavaScript.
    • Performance is better, especially on mobile.

CSS: the real engine of the gallery

The stylesheet is one of the aspects that has changed the most compared to previous posts; let's explain the main rules:

Positioning the images (position: relative/fixed)

One of the changes presented is the addition of the position property to alter the flow of positioning for HTML elements like images:

#container div{
    position: relative;
    transition: width 1s, width 1s, top 1s;
    z-index:1;
    /*mas CSS*/
}

Additionally, the incorporation of CSS Transitions for smooth changes between one state and another; the idea is to smoothly place the selected image in the center of the screen at a larger size when a click is detected through JavaScript that adds the select class:

#container div.select{
    position: fixed;	
    width: 100%;
    height: 100%;
    top: 0;
    left:0;
    z-index:5;
}

In other words, by adding the select class, the transition defined in the CSS is automatically activated among other properties.

A key factor here is position: fixed; to place the image in an absolute manner centered on the screen and independent of the rest of the content.

We also modify the left margin of the image adjacent to the selected image:

#container div.select + div{
    margin: 5px 3% 5px 31%;
}

The 31% value is the sum of the right margin (3%) plus the size of the image container (28%); this prevents the adjacent element from taking the place of the selected image and disrupting the behavior of the entire gallery.

Smooth transitions when selecting an image

Thanks to transition, the change between states is not abrupt. The CSS handles animating the transition from a small image to an enlarged image.

How to center the image without breaking the layout

One of the most common problems I found was that, when opening an image, the rest of the layout became disorganized. To avoid this, we adjust the margin of the adjacent element:

#container div.select + div{
 margin: 5px 3% 5px 31%;
}

That 31% is the sum of the margin and the width of the original container, which prevents elements from "jumping" out of place.

Making the gallery responsive without libraries: Adaptation to different screen sizes

This gallery works well on large and small screens without the need for frameworks. The CSS controls the visual behavior and the JavaScript remains the same.

Best practices with responsive images

If you want to optimize even further, you can use responsive images (srcset) to serve different sizes depending on the device. In this case, since it's a simple gallery, it's not always mandatory, but it's an interesting improvement for larger projects.

When to use srcset and when it's not necessary

In my tests, I only recommend srcset when:

  • Images are very heavy.
  • There is a lot of mobile traffic.
  • Performance is critical.

Common mistakes when creating a gallery with JavaScript

  • Abusing JavaScript for animations
    • One of the most frequent mistakes is animating everything with JavaScript. CSS is optimized for that and usually offers better results.
  • z-index and positioning issues
    • If the image does not appear on top of the rest, the problem is almost always in the z-index or not using position: fixed.
  • Layout that breaks when opening an image
    • This happens when the space occupied by the original image is not taken into account. Adjusting margins, as we did before, avoids this problem.

Advantages of this gallery compared to other solutions

  • ✅ Only 6 lines of JavaScript
  • ✅ No external libraries
  • ✅ Easy to understand and maintain
  • ✅ CSS as the protagonist
  • ✅ Ideal for small or educational projects
  • After trying alternatives with GSAP and other libraries, this solution ended up being the most practical for many real cases.

Frequently asked questions about image galleries with JavaScript

  • Can a gallery be created without libraries?
    • Yes. As you've seen, CSS and pure JavaScript are more than enough for a functional gallery.
  • Is CSS or JavaScript better for animations?
    • CSS. JavaScript should be limited to controlling states, not animations.
  • How many lines of JavaScript do I actually need?
    • In this case, only six. And often, even fewer.

Conclusion: a simple, maintainable, and functional gallery

If you are looking for a simple JavaScript image gallery, this approach is hard to beat. In my experience, the less JavaScript you use for visual effects, the more stable and maintainable your code will be.

With a clear structure, well-utilized CSS, and minimal JavaScript, you can achieve professional results without overcomplicating things.

You can find the full demo at the following links:

See examples Download source

I agree to receive announcements of interest about this Blog.

Learn how to create a responsive image gallery with HTML and CSS. Step-by-step tutorial with just 6 lines of JavaScript for a fast and lightweight website.

| 👤 Andrés Cruz

🇪🇸 En español