Search code examples
htmlcsscss-grid

Cant figure out how grid works


I am creating a site for a school project and can't figure out how to wrap elements like flex-wrap does. This is the goal that I want to achieve. I can't use flex-box cause we need to use both flex and grid on the page.

img full screen

image smaller screen

.sfeer {
  display: grid;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin: 0 auto;
  padding-top: 5%;
}

.sfeer div {
    display: grid;
    grid-template-columns: repeat(auto-fill, 250px);
    grid-gap: 1rem;
    margin-top: 1rem;
}
.sfeer img {
    display: block;
    width: 250px;
    height: 250px;
    object-fit: cover;
    box-shadow: 0px 0px 3em rgba(0, 0, 0, 0.3);
}
<article class="sfeer">
        <h2>Sfeer foto's</h2>
        <div>
          <img src="https://unsplash.it/640" alt="Foto 1: enkele chiroleden" />
          <img src="https://unsplash.it/640" alt="Foto 2: enkele chiroleden" />
          <img src="https://unsplash.it/640" alt="Foto 3: enkele chiroleden" />
          <img src="https://unsplash.it/640" alt="Foto 4: enkele chiroleden" />
          <img src="https://unsplash.it/640" alt="Foto 5: enkele chiroleden" />
          <img src="https://unsplash.it/640" alt="Foto 6: enkele chiroleden" />
          <img src="https://unsplash.it/640" alt="Foto 7: enkele chiroleden" />
          <img src="https://unsplash.it/640" alt="Foto 8: enkele chiroleden" class="last" />
        </div>
</article>


Solution

  • Stick with a single grid, at least to start with.

    .sfeer div {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      grid-gap: 1rem;
      margin-top: 1rem;
    }
    
    .sfeer img {
      display: block;
      width: 100%;
      aspect-ratio: 1/1;
      object-fit: cover;
      box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
    }
    <article class="sfeer">
      <h2>Sfeer foto's</h2>
      <div>
        <img src="http://picsum.photos/300">
        <img src="http://picsum.photos/300/350">
        <img src="http://picsum.photos/350/300">
        <img src="http://picsum.photos/300/340">
        <img src="http://picsum.photos/340/300">
        <img src="http://picsum.photos/300/330">
        <img src="http://picsum.photos/330/300">
        <img src="http://picsum.photos/300/320">
      </div>
    </article>