我正在尝试用尽可能多的块水平填充我的页面并将结果居中。
我希望当窗口变小时可以调整网格的大小:
wide window
xxx
small window
xx
x
如果没有JavaScript,是否可以实现?
.box {
box-sizing: border-box;
width: 200px;
height: 150px;
background-color: white;
border: solid 6px red;
}
.box:nth-child(2) {
background-color: blue
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
}
<div class="center">
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
以视觉方式进行说明:
尝试使用flexbox。
.box {
box-sizing: border-box;
width: 200px;
height: 150px;
background-color: white;
border: solid 6px red;
}
.box:nth-child(2) {
background-color: blue
}
.grid {
display: flex;
justify-content: center;
align-items: center;
}
@media screen and (max-width: 767px) {
.grid {
flex-wrap: wrap;
justify-content: center;
}
.box {
width: 50%
}
<div class="center">
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
自动拟合和自动填充需要一个已知的宽度来计算,我们可以使用max-width:100%
而不是固定宽度来进行计算。
.box {
box-sizing: border-box;
width: 200px;
height: 150px;
background-color: white;
border: solid 6px red;
}
.box:nth-child(2) {
background-color: blue
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
max-width: 100%;
}
.center {
display: flex;
flex-direction: column;
align-items: center;
}
<div class="center">
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>