2

I've got a navigation which looks sort like a this one under, and li items inside are flex items. This menu is rendered from the outside, and I'm not able to wrap any of the items inside the dedicated container.

What I'm trying to achieve is to set space-between between the last item and the other ones on the left. I've tried to do it with a margin-left on the last child, but it's not a nicest solution.

Is there a CSS option to "wrap" the last item somehow, so there's always space between that one and the ones on the left?

.container {
  max-width: 1000px;
  background-color: lightblue;
}

ul {
  display: flex;
  justify-content: space-between;
}

.last {
  background: red;
}
<div class="container">
  <ul>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li class="last">Last Item</li>
  </ul>
</div>
Smithy
  • 807
  • 5
  • 17
  • 43
  • why do you call margin-left solution as a "not-nicest"? It's a good practice, which is used frequently for this kind of tasks. – flppv Oct 13 '20 at 11:00
  • Margin solution is a good one: https://medium.com/@iamryanyu/how-to-align-last-flex-item-to-right-73512e4e5912 – m4n0 Oct 13 '20 at 11:01
  • Yeah I know, but since the width of the screen will be different for different monitor sizes - with margin I can't make it stick to the left at all times – Smithy Oct 13 '20 at 11:15
  • you need margin-left:auto on the last child (no need extra wrapper) – Temani Afif Oct 13 '20 at 11:26

1 Answers1

2

Using margin-left on the last element is a good solution. However, you can improve your implementation by using the :last-child selector:

ul li:last-child {
  margin-left: 10px;
}

Instead of manually assigning the last class to the last child.

EDIT: If you mean you want your last child to be aligned all the way to the right. You can separate them into different lists, and use justify-content: space-between:

.container {
  max-width: 1000px;
  background-color: lightblue;
  display: flex;
  justify-content: space-between;
}

ul {
  display: flex;
}

ul li {
  width: 3rem;
}

.right li {
  background-color: red;
}
<div class="container">
  <ul class="left">
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
  </ul>
  <ul class="right">
    <li>Item</li>
  </ul>
</div>
Eddie Reeder
  • 805
  • 1
  • 7
  • 13