gpt4 book ai didi

css - 左、中、右对齐 3 个不相等的 block

转载 作者:行者123 更新时间:2023-11-28 11:55:00 24 4
gpt4 key购买 nike

我正在尝试对齐由 3 个内容 block 组成的顶部菜单。

我想要实现的是:

  • block 1:左对齐
  • block 2:水平居中
  • block 3:右对齐

如果所有 3 个 block 的大小都相同,我可以使用 flexbox(如代码片段中所示),但它们不是,所以它不会产生我需要的输出。

相反,flexbox 在 3 个 block 之间放置相等的空间 - 导致中间 block 偏离中心对齐。

我想知道这是否可以通过 flexbox 实现,或者如果不能,另一种解决方案。这需要在生产中稳健运行,因此“网格”解决方案不适用,因为支持不足。

.container {
margin: 20px 0;
}

.row {
background-color: lime;
display: flex;
justify-content: space-between;
}

.item {
background-color: blue;
color: #fff;
padding: 16px;
}
<div class="container">
<div class="row">
<div class="item">left, slightly longer</div>
<div class="item">center, this item is much longer</div>
<div class="item">right</div>
</div>
</div>

最佳答案

您可以考虑为左右元素使用 flex-grow:1;flex-basis:0%,然后使用 text-align 对齐内部内容。我添加了一个额外的包装器,以仅在文本周围保留背景。

诀窍是通过仅删除中间内容并将其平均分配给左右元素来计算可用空间。

.container {
margin: 20px 0;
padding-top:10px;
background:linear-gradient(#000,#000) center/5px 100% no-repeat; /*the center*/
}

.row {
background-color: lime;
display: flex;
color: #fff;
}

.item:not(:nth-child(2)) {
flex-basis: 0%;
flex-grow: 1;
}

.item:last-child {
text-align: right;
}

.item span{
background-color: blue;
display:inline-block;
padding: 16px;
border: 2px solid red;
box-sizing:border-box;
}
<div class="container">
<div class="row">
<div class="item"><span>left, slightly longer</span></div>
<div class="item"><span>center, this item is much longer</span></div>
<div class="item"><span>right</span></div>
</div>
</div>

您也可以通过使元素靠近来实现同样的效果。只需调整文本对齐:

.container {
margin: 20px 0;
padding-top: 10px;
background: linear-gradient(#000, #000) center/5px 100% no-repeat; /*the center*/
}

.row {
background-color: lime;
display: flex;
color: #fff;
}

.item:not(:nth-child(2)) {
flex-basis: 0%;
flex-grow: 1;
}

.item:first-child {
text-align: right;
}

.item span {
background-color: blue;
display: inline-block;
padding: 16px;
border: 2px solid red;
box-sizing: border-box;
}
<div class="container">
<div class="row">
<div class="item"><span>left, slightly longer</span></div>
<div class="item"><span>center, this item is much longer</span></div>
<div class="item"><span>right</span></div>
</div>
</div>

关于css - 左、中、右对齐 3 个不相等的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55393088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com