Search code examples
htmlcssfluid-layoutcss-grid

Maintain aspect ratio of elements within a fluid CSS grid layout


I have a list of div elements in a 4-column CSS grid layout. The div elements are set to 100% width, with a padding-top of 100% to maintain an aspect ratio of 1:1. This is a common technique, as can be seen here: https://stackoverflow.com/a/6615994/7949834

This works in Firefox, but not in Chrome. In Chrome the elements do not take up any space within the grid container. What is the reason for this?

ul {
  border: 2px solid red;
  display: grid;
  grid-gap: 5%;
  grid-template-columns: auto auto auto auto;
  list-style-type: none;
}

div {
  background-color: green;
  padding-top: 100%;
  width: 100%;
}
<ul>
  <li>
    <div></div>
  </li>
  <li>
    <div></div>
  </li>
  <li>
    <div></div>
  </li>
  <li>
    <div></div>
  </li>
  <li>
    <div></div>
  </li>
  <li>
    <div></div>
  </li>
  <li>
    <div></div>
  </li>
  <li>
    <div></div>
  </li>
</ul>

https://jsfiddle.net/ab0asum3/


Solution

  • There appear to be 2 issues:

    • auto is not a valid value for grid-template-columns - use something like 1fr
    • using a percentage value for the grid-gap when no explicit height has been defined for the li or div

    You'll need to use a pixel value for the row gap.

    ul {
      border: 2px solid red;
      display: grid;
      grid-gap: 10px 5%;
      grid-template-columns: repeat(4, 1fr);
      list-style-type: none;
      padding: 0;
      margin: 0;
    }
    
    div {
      background-color: green;
      padding-top: 100%;
      width: 100%;
    }
    <ul>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
    </ul>