我开始学习使用CSS网格。我正在制作一个有looking like this的网格。我需要项目3和4水平对齐项目1。
所有物品的高度应为700px,因此该部分应适合。我在想如果我在行和列的代码中做错了什么?
.wrapper {
display: grid;
grid-template-columns: repeat(11, 1fr);
grid-gap: 1em;
}
.wrapper>div {
background-color: #eee;
padding: 1em;
}
.wrapper>div:nth-child(odd) {
background-color: #ddd;
}
.item1 {
grid-row: 1 / 3;
grid-column: 1/6;
height: 700px;
}
.item2 {
grid-row: 1 / 1;
grid-column: 6/12;
height: 340px;
}
.item3 {
grid-row: 2 / 3;
grid-column: 6/9;
height: 350px;
}
.item4 {
grid-row: 2/3;
grid-column: 9/12;
height: 350px;
}
<div class="wrapper">
<div class="item1">
This is item 1
</div>
<div class="item2">
This is item 2
</div>
<div class="item3">
This is item 3
</div>
<div class="item4">
This is item 4
</div>
</div>
一些改变应该有所帮助。首先,将grid-gap
上的wrapper
从1em
改为10px
。这有助于1em的间隙问题,默认情况下通常为16px。然后只需将box-sizing: border-box;
添加到.wrapper > div
。
这是一个有效的例子:
.wrapper {
display:grid;
grid-template-columns:repeat(11,1fr);
grid-gap: 10px;
}
.wrapper > div {
background-color: #eee;
padding: 1em;
box-sizing: border-box;
}
.wrapper > div:nth-child(odd) {
background-color: #ddd;
}
.item1 {
grid-row: 1 / 3;
grid-column: 1/6;
height: 700px;
}
.item2 {
grid-row: 1 / 1;
grid-column: 6/12;
height: 340px;
}
.item3 {
grid-row: 2 / 3;
grid-column: 6/9;
height: 350px;
}
.item4 {
grid-row:2/3;
grid-column: 9/12;
height: 350px;
}
<div class="wrapper">
<div class="item1">
This is item 1
</div>
<div class="item2">
This is item 2
</div>
<div class="item3">
This is item 3
</div>
<div class="item4">
This is item 4
</div>
</div>
你的问题是每个网格元素上的padding:1em
。这使它们比你期望的更大。
我在下面修改了你的例子。我希望这有帮助 :-)
.wrapper {
display: grid;
grid-template-columns: repeat(11, 1fr);
grid-gap: 1em;
}
.wrapper > div {
background-color: #eee;
padding: 1em;
}
.wrapper > div:nth-child(odd) {
background-color: #ddd;
}
.item1 {
grid-row: 1 / 3;
grid-column: 1/6;
height: 700px;
}
.item2 {
grid-row: 1 / 1;
grid-column: 6/12;
}
.item3 {
grid-row: 2 / 3;
grid-column: 6/9;
}
.item4 {
grid-row: 2/3;
grid-column: 9/12;
}
<div class="wrapper">
<div class="item1">This is item 1</div>
<div class="item2">This is item 2</div>
<div class="item3">This is item 3</div>
<div class="item4">This is item 4</div>
</div>