Search code examples
htmlcssuser-interfaceflexboxgrid

How to create a basic gallery grid using an unordered list


Using flex, I'm trying to create a gallery grid using an unordered list item.

It requires the first image to be 50%, then the other 4 images alongside it in a grid.

I have attached a js fiddle and an image of what I'm after, as I can't figure out where I'm going wrong.

http://jsfiddle.net/qj7u5tv6/

grid gallery using flex

li:first-child{
  width: 50%;
} 

li:not(:first-child)  {
  width: 25%;
  flex-direction: row;
  display: flex;
  flex-wrap: wrap;
  
}

Thanks

Solution

  • Using grid it's pretty trivial.

    Your layout is basically a two rows and 3 columns layout.
    Both rows take 50% of the height or in fraction 1fr, while for first column takes 50% of the width and the others 25% or in fraction: 2fr, 1fr and 1fr.

    The first image spans across the two rows.

    ul {
      list-style: none;
      display: grid;
      grid-template-columns: 2fr 1fr 1fr;
      grid-template-rows: 1fr 1fr;
    }
    
    li:first-child {
      grid-row: span 2;
    }
    

    If you want a gap, you can add it to the grid:

      gap: 1rem;
    

    To have the pictures fill their cells:

    img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    

    Snippet:

    * {
      margin: 0px;
      padding: 0px;
    }
    
    ul {
      list-style: none;
      display: grid;
      grid-template-columns: 2fr 1fr 1fr;
      grid-template-rows: 1fr 1fr;
      gap: 1rem;
    }
    
    li:first-child {
      grid-row: span 2;
    }
    
    img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    <ul>
      <li>
        <img src="https://via.placeholder.com/400" />
      </li>
      <li>
        <img src="https://via.placeholder.com/400" />
      </li>
      <li>
        <img src="https://via.placeholder.com/400" />
      </li>
      <li>
        <img src="https://via.placeholder.com/400" />
      </li>
      <li>
        <img src="https://via.placeholder.com/400" />
      </li>
    </ul>