CSS网格“响应”列在可用空间上增长或缩小(没有固定宽度)

问题描述 投票:0回答:1

我将有一个有时会有1、2、3或4列的网格。

这里是两列的示例。

* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;

}
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
  grid-auto-rows: 50px 100px;
}
<div class="wrapper">
   <div>One</div>
   <div>Two</div>
   <div>Three</div>
   <div>Four</div>
   <div>Five</div>
   <div>Six</div>
   <div>Seven</div>
   <div>Eight</div>
    <div>Nine</div>
</div>

https://codepen.io/alfaex/pen/QWbPRxw

在这种情况下,我希望第九项跨到第二列。

我找不到第九项说“刚刚成长”的属性

当媒体查询3列时,grid-template-columns: 1fr 1fr;grid-template-columns: 1fr 1fr 1fr;它应该再次占据1fr

[1fr 1fr 1fr 1fr1fr 1fr有相同的问题

css css-grid
1个回答
0
投票

考虑last-child选择器,使其在行中仅有一个时跨整个行:

.wrapper :last-child:nth-child(odd) {
  grid-column: 1 / -1;
}

如果您拥有多于两列,则可以执行相同的逻辑。

* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;

}
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}


.three {
  grid-template-columns: 1fr 1fr 1fr;
}
.four {
  grid-template-columns: 1fr 1fr 1fr 1fr;
}

.wrapper.four :last-child:nth-child(4n + 1),
.wrapper.two :last-child:nth-child(odd){
  grid-column:1/-1;
}
<div class="wrapper two">
   <div>One</div>
   <div>Two</div>
   <div>Three</div>
   <div>Four</div>
   <div>Five</div>
   <div>Six</div>
   <div>Seven</div>
   <div>Eight</div>
    <div>Nine</div>
</div>

<div class="wrapper three">
   <div>One</div>
   <div>Two</div>
   <div>Three</div>
   <div>Four</div>
   <div>Five</div>
   <div>Six</div>
   <div>Seven</div>
   <div>Eight</div>
    <div>Nine</div>
</div>

<div class="wrapper four">
   <div>One</div>
   <div>Two</div>
   <div>Three</div>
   <div>Four</div>
   <div>Five</div>
   <div>Six</div>
   <div>Seven</div>
   <div>Eight</div>
    <div>Nine</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.