我正在创建4x3网格布局,并希望第二行居中,因为第一行有四个元素。
类似这样的东西:
演示代码:
.grid-container {
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-template-rows: 50% 50%;
padding: 10px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
</div>
答案 0 :(得分:1)
易于使用flex
并使用justify-content: center;
居中设置宽度,使用flex: 0 0 cala(20% - 40px);
:
.grid-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
font-size: 30px;
text-align: center;
flex: 0 0 calc(20% - 40px);
padding: 20px;
margin: 5px;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
</div>
答案 1 :(得分:1)
实际上,您需要一个 8 列网格。
.grid-container {
display: grid;
grid-template-columns: repeat(8, 1fr);
grid-template-rows: 50% 50%;
padding: 10px;
grid-gap: 4px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
grid-column: span 2
}
.grid-item:nth-child(5) {
grid-column: 2 / span 2;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
</div>