【问题标题】:flexbox space-between and align rightflexbox space-between and align right
【发布时间】:2016-01-21 13:37:42
【问题描述】:

我有一个包含 1 到 3 个项目的 div,我希望它们的行为如下:

  1. 三项:用justify-content: space-between取整行

    +-----------+
    | 1 | 2 | 3 |
    +-----------+
    
  2. 如果只有 1 项,则将其向右对齐。

    +-----------+
    |       | 3 |
    +-----------+
    

这是我的代码:

.container {
  display: flex;
  width: 300px;
  justify-content: space-between;
  /* Styling only */
  padding: 10px;
  background: #ccc;
  margin-bottom: 10px;
}
.container div {
  /* Styling only */
  background: white;
  padding: 20px 40px;
  width: 10px;
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div>
    3
  </div>
</div>

<div class="container">
  <div>
    3
  </div>
</div>

我找到了direction: rtl 的解决方案,但我希望有一个不那么老套的解决方案,我不想重新排序我的 dom。

有什么想法吗?

【问题讨论】:

  • 方向:rtl 实际上不是 hack。

标签: css flexbox


【解决方案1】:

从此改变

.container {
    justify-content: space-between;
}

.container {
    justify-content: flex-end;
}

【讨论】:

  • 这只会向右对齐,但会删除之间的空格
【解决方案2】:

使用 flex-direction 属性

.container {
  flex-direction:row-reverse;
}

.container {
  display: flex;
  width: 300px;
  justify-content: space-between;
  flex-direction:row-reverse;
  /* Styling only */
  padding: 10px;
  background: #ccc;
  margin-bottom: 10px;
}
.container div {
  /* Styling only */
  background: white;
  padding: 20px 40px;
  width: 10px;
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div>
    3
  </div>
</div>

<div class="container">
  <div>
    3
  </div>
</div>

【讨论】:

  • 不幸的是,这会重新排序 DOM,而 OP 不想这样做。如果有多个项目,则排序为 [1, 2, 3] 的单元格将改为排序 [3, 2, 1]。
【解决方案3】:

有一个选择器。

.container div:only-child {
  margin-left: auto;
}

.container {
  display: flex;
  width: 300px;
  justify-content: space-between;
  /* Styling only */
  padding: 10px;
  background: #ccc;
  margin-bottom: 10px;
}
.container div {
  /* Styling only */
  background: white;
  padding: 20px 40px;
  width: 10px;
}
.container div:only-child {
  align-self: flex-end;
  margin-left: auto;
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div>
    3
  </div>
</div>

<div class="container">
  <div>
    3
  </div>
</div>

【讨论】:

  • 事实上,使用margin-left: auto 就足够了,即使没有only-child 选择器。谢谢!
  • 在我的测试中,在最后一个孩子上使用margin-left: auto 会导致所有较早的孩子被推到最左边,就好像他们都是justify-content: flex-start,所以only-child 是实际的解决方案。 codepen example
  • 对于有一个可见的孩子,而其他孩子使用 display: none 而不是从 dom 中完全删除的情况,这是一个问题——:only-child 将不起作用案例。
  • 没有理由应该......这个问题绝不会引用display:none,如果它有替代解决方案将是合适的。 CSS 选择 DOM 中的元素,无论它们是否可见。
  • @HugoH margin-left: auto 单独是不够的如果你真的想保留在项目之间分配可用空间的效果。当您将左边距设置为auto 时,现在右对齐容器中的项目之间的其他可用空间折叠,因此您的justify-content: space-between 规则变得无用——它适用,但没有免费的无论如何,在项目之间分配空间。当你说“足够”时要准确——对于你的用例来说可能已经足够了,但不要搞错——CSS会按照你的指示去做。毕竟,也许您之间不需要任何空间?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
相关资源
最近更新 更多