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

标签 css flexbox

我正在尝试对齐由 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/59513745/

相关文章:

html - Flexbox 重新排列 2 个嵌套元素之间的顺序

jquery - 无效选择的 JQM (jQueryMobile) 自定义 css

python - 如何编写正则表达式以从 CSS 文件中提取特定的键格式和值?

css - 使用 flexbox 垂直居中元素

css - 带有响应正方形的网格布局

html - css flex 布局不适用于某些 iPad

css - 固定跨度宽度

jquery - 我的一些元素通过 appendTo() 通过我的粘性页脚

html - 奇怪的白色东西出现在鼠标悬停 CSS 按钮上

html - 将文本内容添加到 div 会导致内联 block 元素被撞下