Shrink grid items just like flex items in css

喜欢而已 提交于 2019-12-05 13:52:36

One solution is to specify a max-width to the child element relying on the viewport unit since percentage values are relative to the size of the track defined by the minmax() and cannot be used. This solution isn't generic and you need to adjust the value depending on each situation.

In you case for example, we can use 100vw since the container is the only element in the body and is taking the whole width:

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

.child {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
  border: 3px solid #a07;
  max-width:100vw;
  box-sizing:border-box; /* Don't forget this !*/
}

body {
  margin:0;
}
<div class="container">
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
</div>

In case there is more element or some padding/margin you need to consider them within the max-width calculation:

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

.child {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
  border: 3px solid #a07;
  max-width:calc(100vw - 40px); /*we remove the body margin*/
  box-sizing:border-box; 
}

body {
  margin:0 20px; 
}
<div class="container">
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
  <div class="child">
    text
  </div>
</div>

It's like we no more have 2 constraints but 3:

  • The grid cell has a minimum size of 200px
  • The grid cell fill the remain space
  • The element inside the grid cell has a maximum size defined relatively to the screen size. (the shrink constraint we were missing)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!