flexbox space-between and align right

守給你的承諾、 提交于 2021-02-15 12:03:15

问题


I have a div with 1 to 3 items and I want them to behave like this :

  1. Three items : take the whole line with justify-content: space-between

    +-----------+
    | 1 | 2 | 3 |
    +-----------+
    
  2. If there is only 1 item, align it to the right.

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

Here's my code :

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

I've found a solution with direction: rtl, but I hope there's a less hacky solution, and I prefer not to reorder my dom.

Any ideas?


回答1:


There is a selector for that.

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



回答2:


Use flex-direction property

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



回答3:


Change from this

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

TO

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


来源:https://stackoverflow.com/questions/33278246/flexbox-space-between-and-align-right

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!