我有一个 CSS 网格容器,有 3 个子容器,它们的宽度都不同。我希望两个侧面的 child 位于容器的两侧,中间的 child 位于中心。
我尝试将第一个设置为 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>
我是不是漏掉了什么?这不可能吗?
最佳答案
您可以将网格用于外部元素,并使用绝对位置和变换将中间元素居中,如下所示:
.container {
display: grid;
grid-template-columns: auto auto;
height: 100px;
position:relative;
width:100%;
}
.first {
justify-self: start;
background-color: red;
width: 50px;
}
.middle {
background-color: green;
width: 70px;
position:absolute;
left: 50%;
transform: translateX(-50%);
height:100%;
}
.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>
但请注意,使用此方法元素可能会重叠。
关于html - 无论 sibling 的宽度如何,都将网格子项居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56157586/