【问题标题】:Center when only a single item in flexbox [duplicate]当flexbox中只有一个项目时居中[重复]
【发布时间】:2017-12-24 17:15:36
【问题描述】:

我有一个 flexbox 控制的页脚。它可以包含 1,2 或 3 个从属 div。

.footer {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

<div class='footer'>
  <div>Left</div>
  <div>Middle</div>
  <div>Right</div>
</div>

使用 2 或 3 个 div,上面的 css 可以正常工作:

  • 三个,LeftRight左右齐平,Middle在中间。
  • 用 2 左右冲洗

但是对于单个 div,它是左对齐的。我希望它居中。

如何调整 css 以便在单个 div 的情况下居中,同时保留 2 或 3 个 div 的行为?

【问题讨论】:

标签: html css flexbox


【解决方案1】:
.footer > :only-child
{
    margin-left: auto;
    margin-right: auto;
}

【讨论】:

  • 有什么理由不使用margin: auto
  • 它在最初的答案中。但是正如 cmets 中指出的(然后被删除),您最好不要在不需要时覆盖规则。
【解决方案2】:

您可以确保您的项目随着可用空间的增长而增长,因此它们的内容将相对于项目定位

.footer > div {
   flex-grow:1:
   text-align: center; // for example
}

.footer {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.footer > div {
 flex-grow:1;
 text-align:center; //for example
}
<div class='footer'>
  <div>Left</div>
  <div>Middle</div>
  <div>Right</div>
</div>

【讨论】:

    【解决方案3】:

    如果您只想使用边距,请调整边距,您可以使用space-evenly,或者使用伪元素和您现有的space-between 进行跨浏览器技巧

    堆栈 sn-p - + space-between

    .footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .footer::before, .footer::after {
      content: '';
    }
    <div class='footer'>
      <div>Left</div>
      <div>Middle</div>
      <div>Right</div>
    </div>

    堆栈 sn-p - space-evenly (browser support)

    .footer {
      display: flex;
      align-items: center;
      justify-content: space-evenly;
    }
    <div class='footer'>
      <div>Left</div>
      <div>Middle</div>
      <div>Right</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2015-10-26
      • 2014-10-21
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 2016-08-31
      • 2020-06-17
      • 1970-01-01
      相关资源
      最近更新 更多