html - 当边项具有不同宽度时,保持中间项居中

标签 html css flexbox centering

enter image description here

想象一下下面的布局,其中点代表框之间的空间:

[Left box]......[Center box]......[Right box]

当我删除右边的框时,我希望中心框仍然位于中心,如下所示:

[Left box]......[Center box].................

如果我删除左边的框,同样如此。

................[Center box].................

现在,当中心框中的内容变长时,它将根据需要占用尽可能多的可用空间,同时保持居中。左右框永远不会收缩,因此当没有空间时,overflow:hiddentext-overflow: ellipsis 将生效以中断内容;

[Left box][Center boxxxxxxxxxxxxx][Right box]

以上都是我的理想情况,但是我不知道如何实现这个效果。因为当我像这样创建一个 flex 结构时:

.parent {
    display : flex; // flex box
    justify-content : space-between; // horizontal alignment
    align-content   : center; // vertical alignment
}

如果左右方框的大小完全相同,我就会得到想要的效果。但是,当两者之一的尺寸不同时,居中框不再真正居中。

有没有人可以帮助我?

更新

justify-self 会很好,这很理想:

.leftBox {
     justify-self : flex-start;
}

.rightBox {
    justify-self : flex-end;
}

最佳答案

If the left and right boxes would be exactly the same size, I get the desired effect. However when one of the two is a different size the centered box is not truly centered anymore. Is there anyone that can help me?

这里有一个使用 flexbox 使中间元素居中的方法,无论 sibling 的宽度如何。

主要特点:

  • 纯 CSS
  • 没有绝对定位
  • 没有 JS/jQuery

使用嵌套的 flex 容器和 auto 边距:

.container {
  display: flex;
}
.box {
  flex: 1;
  display: flex;
  justify-content: center;
}

.box:first-child > span { margin-right: auto; }

.box:last-child  > span { margin-left: auto;  }

/* non-essential */
.box {
  align-items: center;
  border: 1px solid #ccc;
  background-color: lightgreen;
  height: 40px;
}
p {
  text-align: center;
  margin: 5px 0 0 0;
}
<div class="container">
  <div class="box"><span>short text</span></div>
  <div class="box"><span>centered text</span></div>
  <div class="box"><span>loooooooooooooooong text</span></div>
</div>
<p>&#8593;<br>true center</p>

这是它的工作原理:

  • 顶级 div (.container) 是一个 flex 容器。
  • 每个子 div (.box) 现在都是一个 flex 元素。
  • 每个 .box 项都被赋予 flex: 1 以便平均分配容器空间 (more details)。
  • 现在元素占用了行中的所有空间并且宽度相等。
  • 使每个元素成为(嵌套的) flex 容器并添加 justify-content: center
  • 现在每个 span 元素都是一个居中的 flex 元素。
  • 使用 flex auto 边距左右移动外部 span

您也可以放弃 justify-content 并专门使用 auto 边距。

但是 justify-content 可以在这里工作,因为 auto 边距总是优先的。

8.1. Aligning with auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

关于html - 当边项具有不同宽度时,保持中间项居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52064576/

相关文章:

javascript - 如何根据选择选项框中的选择显示数组值?

css可变宽度2个盒子

html - 在同一页面上将菜单项中的视频打开到 iframe 中

css - 100% 高垂直选取框,CSS 固定滚动速度

css - 以最大宽度居中内容且不使用边距

javascript - 我无法让鼠标瞄准正常工作

html - 删除 h1 和 h2 之间的空格

javascript - jQuery UI(在屏幕上可见时运行)

html - Flexbox 没有占用包装器的全部高度

javascript - 如何在flexslider的每张幻灯片中显示6张图片?