如何使用CSS网格创建两列网格? [英] How to create a two column grid using CSS grid?
问题描述
我正在尝试创建一个相当简单的布局,并且我想避免使用浮点数。我的简化HTML如下所示,因此,我现在尝试创建一个两列的布局,其中我希望项目B在左侧,项目A,C和D在右侧(彼此下方)。我尝试使用的代码是:
I'm trying to create a fairly simple layout, and I want to avoid using floats. My simplified HTML is as follows, and so now I'm trying to create a two column layout, in which I would like to have item B on the left, and items A, C and D on the right (underneath eachother). The Code I tried using is:
.container {
display: grid;
grid-template-areas: 'left right';
}
.item-b {
grid-area: left;
}
.item:not(.item-b) {
grid-area: right;
}
<div class="container">
<div class="item item-a">A</div>
<div class="item item-b">B</div>
<div class="item item-c">C</div>
<div class="item item-d">D</div>
</div>
但是在这里,右边的项目被放置在彼此的顶部。有什么办法可以将它们放置在彼此下面吗?这是带有相同代码的小提琴: https://jsfiddle.net/b85h7g03/
But here, the items on the right are being placed on top of eachother. Is there any way to place them underneath eachother? Here is a fiddle with the same code: https://jsfiddle.net/b85h7g03/
此外,当您看小提琴时,为什么这些物品不再是容器的50%了?
Also, when you look at the fiddle, why are the items not 50% of the with of the container anymore?
(顺便说一句,我之所以不在HTML中将项目B放在项目A上方,是因为在移动设备上项目B必须在项目A下方)
(By the way, the reason I'm not placing item B above item A in my HTML, is because on mobile item B needs to be below item A)
:我刚刚更新了小提琴: https://jsfiddle.net/b85h7g03/2/ 我忘了提到项目B的高度灵活,可以变长。供参考:这是我想要的布局,但没有浮点数: https://jsfiddle.net/hLx3709v/
I just updated my fiddle: https://jsfiddle.net/b85h7g03/2/ I forgot to mention that item B has a flexible height and can get very long. For reference: This is the layout I want, but without floats: https://jsfiddle.net/hLx3709v/
推荐答案
在这里,您可以使用flex
Here you go by using flex
<div class="container">
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
</div>
CSS
* {
box-sizing: border-box;
}
body, html {
margin: 0;
padding: 0;
}
.container {
height: 100vh;
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
.children {
width: calc(50% - 10px);
margin: 5px;
background: #D8D8D8;
flex: 1;
}
.children:first-child {
flex: 0 0 calc(100% - 10px);
border: 2px solid #44C0FF;
}
这篇关于如何使用CSS网格创建两列网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!