Search code examples
htmlcssgrid-layoutcss-grid

CSS grid items based on minimum width and percentage


I currently have a div style as a grid display. The grid-template-columns are each 1/3 of the body. However, I would like to limit each box to a minimum width of, say, 200px. This way, on mobile I won't have three extremely skinny boxes. Is there any way to do this, or am I approaching the problem in completely the wrong way?

.wrapper {
  display: grid;
  grid-template-columns: 33% 33% 33%;
  grid-gap: 10px;
  background-color: #fff;
  color: #444;
}

.box {
  background-color: #444;
  border-color: #Dd6161;
  border-style: solid;
  border-width: 2px;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 14px;
}

Solution

  • This might be what you're looking for if you only have three boxes in the wrapper and you want them to wrap onto another row if the wrapper is less than 600px.

    .wrapper {
      display: grid;
      grid-gap: 10px;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }
    

    What this does is:

    1. repeat - this just tells the gird to do the following multiple times.
    2. auto-fit - this is the first argument inside the 'repeat' and tells the grid to 'fit the columns in the grid by expanding them to take the entire space of the grid. It also means if the items don't fit in a single row they will wrap.
    3. minmax(200px, 1fr) means that each column in the grid will be a minimum of 200px and a max of an equal amount of space (so if there are three items, it will be 33.333% each).

    Here is an example: https://codepen.io/chrisboon27/pen/RMjGme

    Alternately if you want them to all become full width (so one column of three rows) you would use grid-template-columns: repeat(3, minmax(200px, 1fr)); and then use a media query to change it to grid-template-columns: 1fr; to make it a single column:

    .wrapper {
      display: grid;
      grid-gap: 10px;
      grid-template-columns: repeat(3, minmax(200px, 1fr));
    }
    @media (max-width: 600px){
      .wrapper{
        grid-template-columns: 1fr;
      }
    }
    

    Here is an example of this one: https://codepen.io/chrisboon27/pen/pLdNjb