调整空格并向右对齐



我有一个包含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。

任何想法?

有一个选择器。

.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>

使用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>

变化从这个

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

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

最新更新