html - 包裹中心网格项目
问题描述
我想弄清楚如何将第三个 div 居中。所以在全宽上,我在一个网格中有 3 个框。它们的宽度为 400 像素。当宽度为 1220px 时,连续变成 2 个框。所以我的第三个盒子是左对齐的。我如何在不破坏宽度的情况下将其居中。因为我试过margin: 0 auto
了,它只是让它和里面的东西一样宽。
这是我的代码:
.wraper {
display: grid;
grid-template-columns: 400px 400px 400px;
grid-gap: 10px;
grid-template-columns: repeat(3, 400px);
}
.box {
background-color: red;
height: 200px;
}
@media (max-width: 1220px) {
.wraper {
grid-template-columns: repeat(2, 400px);
}
}
@media (max-width: 810px) {
.wraper {
grid-template-columns: repeat(1, 400px);
}
}
@media (max-width: 400px) {
.wraper {
grid-template-columns: repeat(1, 300px);
}
}
<div class="block bg-success">
<h1>Projects</h1>
<div class="wraper">
<div class="box">A</div>
<div class="box">B</div>
<div class="box">C</div>
</div>
</div>
解决方案
在您的 1220px 媒体查询中,添加一条规则以使第三个 div 居中。
@media (max-width: 1220px) {
.wrapper {
grid-template-columns: repeat(2, 400px);
}
/* NEW */
.box:last-child {
grid-column: 1 / 3;
justify-self: center;
width: 400px;
}
}
.wrapper {
display: grid;
grid-template-columns: 400px 400px 400px;
grid-auto-rows: 200px;
grid-gap: 10px;
grid-template-columns: repeat(3, 400px);
}
@media (max-width: 1220px) {
.wrapper {
grid-template-columns: repeat(2, 400px);
}
/* NEW */
.box:last-child {
grid-column: 1 / 3;
justify-self: center;
width: 400px;
}
}
@media (max-width: 810px) {
.wrapper {
grid-template-columns: repeat(1, 400px);
}
/* RESET */
.box:last-child {
grid-column: auto;
justify-self: stretch;
width: auto;
}
}
@media (max-width: 400px) {
.wrapper {
grid-template-columns: repeat(1, 300px);
}
}
.box {
background-color: red;
}
<div class="block bg-success">
<h1>Projects</h1>
<div class="wrapper">
<div class="box">A</div>
<div class="box">B</div>
<div class="box">C</div>
</div>
</div>
推荐阅读
- android - CardView:设置背景颜色会移除圆角边缘
- c++ - `closed_iota` 和 `iota` 之间的区别?
- html - 如何在 Selenium 中通过 XPATH 定位元素
- python - 如何从 Decimal 类型的 Python 变量中获取前小数位和小数位?
- android - Google 控制台内部应用程序共享不再有效
- javascript - 如何找到数组中每个对象的平均值
- python - 如何为带有输入的代码编写单元测试(Python)
- android - 在 Android Instrumentation 测试中启动 Fragment 时的几个问题
- node.js - res.render 如果我不使用它,使用 populate() 渲染失败,它可以工作
- javascript - 将展平对象转换为分层对象