Search code examples
htmlcsscss-grid

Shrink columns of CSS grid at the same rate


I am using a css grid. Columns and rows of this grid are set to "auto". Each cell in the grid contains (among other things) an image that determines the dimensions.

The grid looks like this: enter image description here The problem is: when I reduce the screen size, the ratio of the grid cells is not maintained. It seems like the leftmost column is shrunk first:

enter image description here

This leads to ugly wholes in the grid. How can I ensure that the grid is growing and shrinking consistently while ideally keeping the images determining the appearance?

Here is a simple version of the grid CSS with an accompanying fiddle.

   .grid {
    grid-template-columns: auto auto auto;
    grid-template-rows: auto auto auto auto;
    display: grid;
    position: relative;
    grid-gap: 12px 12px;
    }

    .element_1 {
        grid-column-start: 1;
        grid-column-end: 2;
        grid-row-start: 1;
        grid-row-end: 3;
    }
    .element_2 {
          grid-column-start: 2;
        grid-column-end: 4;
        grid-row-start: 1;
        grid-row-end: 4;
    }
    .element_3 {
      grid-column-start: 1;
        grid-column-end: 2;
        grid-row-start: 3;
        grid-row-end: 5;
    }
    .element_4 {
          grid-column-start: 2;
        grid-column-end: 4;
        grid-row-start: 4;
        grid-row-end: 5;
    }

    .img-responsive {
      width: 100%;
      height: auto;
    }

Solution

  • Here is solution, your css file

    .grid {
      display: grid;
    }
    
    .grid > div img {
      display:inline-block;
      vertical-align:middle;
    }
    
    .element_1 {
      grid-column-start: 1;
      grid-column-end: 2;
      grid-row-start: 1;
      grid-row-end: 3;
    }
    .element_1 img {
      padding-top:0;
      padding-left:0;
    }
    .element_2 {
      grid-column-start: 2;
      grid-column-end: 4;
      grid-row-start: 1;
      grid-row-end: 4;
    }
    .element_2 img {
      padding-top:0;
      padding-right:0;
    }
    .element_3 {
      grid-column-start: 1;
      grid-column-end: 2;
      grid-row-start: 3;
      grid-row-end: 5;
    }
    .element_3 img {
      padding-bottom:0;
      padding-left:0;
    }
    .element_4 {
      grid-column-start: 2;
      grid-column-end: 4;
      grid-row-start: 4;
      grid-row-end: 5;
    }
    .element_4 img {
      padding-bottom:0;
      padding-right:0;
    }
    
    .img-responsive {
      box-sizing:border-box;
      padding:6px;
      width: 100%;
      height: auto;
    }
    
    @media screen and (max-width:480px) {
      .img-responsive {
        padding:3px;
      }
    }
    

    you can see running example & play with source code here jsbin