Why does aligning two flex children to the right fail, while aligning one works?

时间:2019-01-15 18:21:01

标签: css flexbox

I have an unordered list with several items. Let's admit is necessary, for whatever reason, for the list to have it's display property set to flex.

If I align one item to the right by setting it's margin-left to auto, that works (unsurprisingly):

.flex-list {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-between;
}

.flex-list li {
  font-family: Arial, sans-serif;
  font-size: 13px;
  padding: 15px 18px;
  border: 1px solid #069;
  color: #777;
  font-weight: bold;
}

.flex-list  .right {
  margin-left: auto;
}
<ul class="flex-list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li class="right">5</li>
</ul>

If instead I want to align two items to the right, that does not work:

.flex-list {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-between;
}

.flex-list li {
  font-family: Arial, sans-serif;
  font-size: 13px;
  padding: 15px 18px;
  border: 1px solid #069;
  color: #777;
  font-weight: bold;
}

.flex-list  .right {
  margin-left: auto;
}
<ul class="flex-list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li class="right">4</li>
  <li class="right">5</li>
</ul>

Why is that? How can I align the last two items to the right?

1 个答案:

答案 0 :(得分:4)

如果仅在第四个元素上设置margin-left: auto,则应获得所需的结果。

.flex-list {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-between;
}

.flex-list li {
  font-family: Arial, sans-serif;
  font-size: 13px;
  padding: 15px 18px;
  border: 1px solid #069;
  color: #777;
  font-weight: bold;
}

.flex-list  .right {
  margin-left: auto;
}
<ul class="flex-list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li class="right">4</li>
  <li>5</li>
</ul>