HTML如何让中间的项居中

使用 Flexbox 的解决方案

可以使用 Flexbox 将中间项居中,而不管同级项的宽度如何。

我们需要使用嵌套的 flex 容器和自动边距。

在下面,我们可以看到它是如何完成的。

使中间项目保持居中的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .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;
      }
      .box {
        align-items: center;
        border: 1px solid #666;
        background-color: #c8cbcf;
        height: 60px;
      }
      p {
        text-align: center;
        margin: 5px 0 0 0;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="box">
        <span>short text</span>
      </div>
      <div class="box">
        <span>centered text</span>
      </div>
      <div class="box">
        <span>经历过风雨,才懂得阳光的温暖。</span>
      </div>
    </div>
  </body>
</html>

其中类名为“container”的 <div> 是一个弹性容器,而类名为“box”的子 <div> 元素是弹性项目。

我们将每个子元素的 flex 属性设置为 1 以平均分配容器空间。

这使得项目使用行中的所有空间并具有相等的宽度。
然后,我们使每个项目成为一个嵌套的 flex 容器,并使用 justify-content 属性和“center”值。

带有“auto”值的 margin-right 和 margin-left 属性分别用于将外部 <span> 元素向右和向左移动。

此解决方案不允许指定宽度。

日期:2020-06-02 22:15:10 来源:oir作者:oir