DEV Community

Cover image for Have you ever tried to create a SQUARED image gallery? CSS only?
Aslam Shah
Aslam Shah

Posted on

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

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);
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

One of the key property to keep the images square is

padding-bottom: calc(var(--width) / var(--items));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
marjanb profile image
marjanb

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.

Collapse
 
hunzaboy profile image
Aslam Shah

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.