我正在尝试使我的css网格为每行2个块(如果有足够的项)或一个横跨整个宽度的块。但是,我似乎无法使用grid-auto-column使其工作。
最上面的块是我想要的样子,最下面的块是我当前的CSS创建的。
.flex1 {
display: flex;
flex-direction: row;
flex: 1;
}
.grid1 {
display: grid;
grid-auto-columns: minmax(50%, 100%);
}
div.height {
height: 50px;
width: 100%;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
<div class="flex1">
<div class="red height">
</div>
<div class="blue height">
</div>
</div>
<div>
<div class="green height">
</div>
</div>
<br><br>
<div class="grid">
<div class="red height">
</div>
<div class="blue height">
</div>
<div class="green height">
</div>
</div>
答案 0 :(得分:1)
使用grid-template-areas: "a b" "c c";
(将.grid1
更改为.grid
,如html一样)
还为grid-area:;
内的每个div设置.grid
.flex1 {
display: flex;
flex-direction: row;
flex: 1;
}
.grid {
display: grid;
grid-auto-columns: minmax(50%, 100%);
grid-template-areas: "a b" "c c";
}
div.height {
height: 50px;
width: 100%;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
<div class="flex1">
<div class="red height">
</div>
<div class="blue height">
</div>
</div>
<div>
<div class="green height">
</div>
</div>
<br><br>
<div class="grid">
<div class="red height" style="grid-area: a;">
</div>
<div class="blue height" style="grid-area: b;">
</div>
<div class="green height" style="grid-area: c;">
</div>
</div>
答案 1 :(得分:1)
不幸的是,据我所知,使用 Grid 不可能做到这一点,但这对于 Flexbox 来说是一项完美而轻松的工作,因为您只需要处理一个或一维布局,在您的情况下为行。
下面,我为您提供 flex-items 所需结果/行为的较短版本,并减少了标记和样式:
.flex {
display: flex;
flex-wrap: wrap; /* enables wrapping of flex-items */
}
.flex > div {
flex: 1 0 50%; /* grows full width if alone in a row / doesn't shrink / initial width set to 50%, i.e. can't be less than 50% of the parent's width */
height: 50px;
}
.red {background: red}
.blue {background: blue}
.green {background: green}
.yellow {background: yellow}
<div class="flex">
<div class="red"></div>
</div>
<br>
<div class="flex">
<div class="red"></div>
<div class="blue"></div>
</div>
<br>
<div class="flex">
<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
</div>
<br>
<div class="flex">
<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>