flexbox space-between和align right

Hug*_*o H 20 css css3 flexbox

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

  1. 三项:全程采取 justify-content: space-between

    +-----------+
    | 1 | 2 | 3 |
    +-----------+
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果只有一个项目,请将其与右侧对齐.

    +-----------+
    |       | 3 |
    +-----------+
    
    Run Code Online (Sandbox Code Playgroud)

这是我的代码:

.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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div>
    3
  </div>
</div>

<div class="container">
  <div>
    3
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我找到了一个解决方案direction: rtl,但我希望有一个不太讨厌的解决方案,我不想重新安排我的dom.

有任何想法吗?

Pau*_*e_D 39

有一个选择器.

.container div:only-child {
  margin-left: auto;
}
Run Code Online (Sandbox Code Playgroud)

.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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div>
    3
  </div>
</div>

<div class="container">
  <div>
    3
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 如果您确实想保留在项目之间分配可用空间的效果,则 @HugoH `margin-left: auto` 单独*是不够的*。当您将左边距设置为“auto”时,现在右对齐容器中的项目之间的可用空间*折叠*,因此您的“justify-content:space- Between”规则变得无用——它适用,但没有无论如何,可以在项目之间分配可用空间。当你说“足够了”时要准确——它可能已经足够满足*你的*用例了,但不要搞错——CSS 会按照你的指示去做。也许你根本不需要任何空间? (3认同)
  • 实际上,即使没有`only-child` slector,使用`margin-left:auto`就足够了.谢谢! (2认同)
  • 在我的测试中,对最后一个孩子使用“ margin-left:auto”会导致所有较早的孩子被推到最左边,就好像它们都是“ justify-content:flex-start”一样,因此“ only-child”是实际的解。[codepen示例](https://codepen.io/anon/pen/aEwrpz) (2认同)

Sau*_*lha 7

使用 flex-direction 属性

.container {
  flex-direction:row-reverse;
}
Run Code Online (Sandbox Code Playgroud)

.container {
  flex-direction:row-reverse;
}
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这会重新排序 DOM,这是 OP 不想做的。如果有多个项目,则排序为 [1, 2, 3] 的单元格将改为排序为 [3, 2, 1]。 (6认同)