【发布时间】:2019-10-03 02:01:36
【问题描述】:
我有一个带有 3 个孩子的 CSS 网格容器,它们的宽度都不同。我希望 2 侧的孩子位于容器的 2 侧,中间的孩子位于容器的中心。
我尝试将第一个设置为justify-self: start,将中间的设置为justify-self: center;,将最后一个设置为justify-self: end;,但它没有居中,它只是平均划分空间。
.container {
display: grid;
grid-template-columns: auto auto auto;
height: 100px;
}
.first {
justify-self: start;
background-color: red;
width: 50px;
}
.middle {
justify-self: center;
background-color: green;
width: 70px;
}
.last {
justify-self: end;
background-color: blue;
width: 200px;
}
<div class="container">
<div class="first"></div>
<div class="middle">Center me</div>
<div class="last"></div>
</div>
我错过了什么吗?这不可能吗?
【问题讨论】:
-
所以你希望列之间的间隙不相等?
-
是的,我希望它居中,即使这意味着不相等的间隙
-
这里是带有 flexbox 的:stackoverflow.com/a/55393886/8620333(带有网格,只需将 auto 替换为 1fr)
-
问题在于渲染引擎不知道将中心列与对齐什么。没有关于兄弟元素的“中心”概念,只有父元素。
-
flexbox 解决方案:stackoverflow.com/questions/43211390