Step 1: Add HTML

Let's add some images first. We will add images as background images.


  <ul class="responsive_gallery">
    <li style="background-image: url(./img/cat.jpg);">
    </li>
    <li style="background-image: url(./img/giraffe.jpg);">
    </li>
    <li style="background-image: url(./img/neptune.jpg);">
    </li>
    <li style="background-image: url(./img/sea.jpg);">
    </li>
    <li style="background-image: url(./img/snail.jpg);">
    </li>
    <li style="background-image: url(./img/space.jpg);">
    </li>
    <li style="background-image: url(./img/superhero.jpg);">
    </li>
    <li style="background-image: url(./img/surfer.jpg);">
    </li>
    <li style="background-image: url(./img/triangle.jpg);">
    </li>
    <li style="background-image: url(./img/psychedelic.jpg);">
    </li>
    <li style="background-image: url(./img/planet.jpg);">
    </li>
    <li style="background-image: url(./img/presents.jpg);">
    </li>
  </ul>

Step 2: Remove margin from body. 

If you want some additional padding around the gallery then keep the margin.


body {
  margin: 0;
}

Step 3: Add style for ul and li elements.

We are removing list styles as we want to use those as image holders.


ul,
li {
  list-style: none;
  padding-left: 0;
  margin: 0;
}

Step 4: Add style for background images.

Keep the background-size the way you want. Cover will keep good proportion of the image with position on center.


li {
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

Step 5: Define CSS Grid for gallery.

auto-fill will keep the full browser width occupied. minmax function will make sure that the image won't go under 300px size and keep using more size if available.

For rows, we want at least 25vh but we don't want the image more than 200px long.


.responsive_gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  grid-auto-rows: minmax(25vh, 200px);
}

Step 6: nth-of-type

What the below CSS does, is select every second list item inside unordered lists and make it take 2 spans in grid.


.responsive_gallery li:nth-of-type(2n + 2) {
  grid-row: span 2;
}

That should create a definitely great responsive image gallery without any media queries.

Download the files from my Github repo: css-grid-responsive-gallery by Yogesh

Checkout the DEMO

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *