html - 在 flex 布局中垂直居中包含内联元素的文本,同时保留空白

标签 html css flexbox

我希望垂直对齐列表项中的文本。我正在使用 display: flex;align-items: center; .但是我的代码包含一个 strong标签,它被解释为一个单独的 flex 元素,因此两侧的空间被折叠。

我可以用   破解它,但是是否有正确的方法让我的带有内联元素的文本垂直居中?

  • 我知道我可以将文本包装在 <p> 中.我正在努力避免这种情况。
  • 我的文字可能足够长,所以 line-height不是一个选择。
  • 一次display: contents;得到广泛支持,这将是我的首选解决方案。

li {
  display: flex;
  align-items: center;
  height: 8em;/* just for example */
  border: 2px solid red;/* just for example */
}
<ul>
  <li>It is <strong>Very important</strong> that this text is vertically centered!</li>
  <li>Also <strong>Very important</strong> that there are spaces in the text.</li>
</ul>

最佳答案

解决您的问题的唯一有效方法是从 flex 格式化上下文中删除文本。您可以通过将文本包装在另一个元素中来实现这一点,使该元素成为 flex 元素。现在您的文本回到了标准的 block 格式上下文,并且折叠空格不再是问题。

li {
  display: flex;
  align-items: center;
  height: 8em;
  border: 2px solid red;
}
<ul>
  <li>
    <p>It is <strong>Very important</strong> that this text is vertically centered!</p>
  </li>
  <li>
    <p>Also <strong>Very important</strong> that there are spaces in the text.</p>
  </li>
</ul>

另外,请注意,无论您指定什么, flex 容器的所有子元素都是 block 级元素。因此,您正在处理内联级元素的想法是不正确的。 flex 容器中没有内联级元素。

§ 4. Flex Items

The display value of a flex item is blockified. If the specified display of an in-flow child of an element generating a flex container is an inline-level value, it computes to its block-level equivalent.

更多详情:

关于html - 在 flex 布局中垂直居中包含内联元素的文本,同时保留空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58825070/

相关文章:

html - 使用 h1 的正确方法? (关于文档大纲和SEO)

html - 如何制作全宽和固定高度的视频

css - 预定义 HTML 时使用 CSS 更改 div 顺序

javascript - 不完全是六 Angular 形的 CSS 边框

css - 如何使用显示柔性将一个元素定位在中心

html - 相对于容器定位内联元素

javascript - 创建导航菜单,一个导航项高于容器的高度

html - 为什么:last-of-type not select the very last cell of a table?

html - 当页面缩小时,Div 文本没有按照我想要的方式 float

html - 当我添加一些交叉淡入淡出图像时,Flexboxes 不会保持正确的高度