loading...
Cover image for Have you ever tried to create a SQUARED image gallery? CSS only?

Have you ever tried to create a SQUARED image gallery? CSS only?

hunzaboy profile image Aslam Shah ・1 min read

Recently, I was trying to create a squared gallery, where all the images are always square, but then I realized it is not that straight forward ;).

What I wanted to achieve was to keep all the images square and also to keep the aspect ratio.

Here is the CSS for the square-gallery parent element.

.square-gallery {
  --items: 7;
  --width: 50vw;
  display: grid;
  grid-template-columns: repeat(var(--items), 1fr);
  background: white;
  width: var(--width);
}

I used grid to create a grid layout for all the gallery items. I have used CSS variables in order to keep the gallery dynamic.

Here is the styling for the gallery item:

.gallery-item {
  display: flex;
  justify-content: center;
  width: calc(var(--width) / var(--items));
  padding-bottom: calc(var(--width) / var(--items));
  background-color: #ff82a9;
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
}

One of the key property to keep the images square is

padding-bottom: calc(var(--width) / var(--items));

Its because the aspect ratio is calculated based on the element instead of the parent.

Or a better way is to use height using the same values

height: calc(var(--width) / var(--items));

The choice is yours.

Here is the final demo with some styling and transitions:

Thanks for reading :)

If you are interested in creating a dark mode via CSS custom properties you can check out my other article: https://dev.to/hunzaboy/the-power-of-css-properties-variables-dark-mode-b8o

Posted on by:

hunzaboy profile

Aslam Shah

@hunzaboy

I am a frontend developer working in Hamburg, Germany. I do a lot of opensource work and currently working on https://codedmails.com as a side project.

Discussion

pic
Editor guide
 

Thank you for the article. Maybe I'm missing something but you could just set padding-bottom to 100% (intrinsics ratio for square is always 100%). No need to calculate anything regarding height, width or padding-bottom.

 

Hey marjanb, you are right but there is one small issue with using percentage values. As per the specs the padding-bottom is based on the parent element's width and not based on the element itself. so that's not the intention here. I hope its clear.