Flexbox - Justify left and right on the same line

Nick Pineda picture Nick Pineda · May 31, 2015 · Viewed 24k times · Source

Situation:

I have a simple nav bar that I'm building in Flexbox. I want to float one item to the left and keep the others pegged to the right.

Example:

<nav>
  <ul class="primary-nav">
    <li><a href="#" id="item1">ListItem1</a></li>
    <li><a href="#" id="item2">ListItem2</a></li>
    <li><a href="#" id="item3">ListItem3</a></li>
    <li><a href="#" id="item4">ListItem4</a></li>
  </ul>
</nav> 

Problem

Typically answers involve just floating items left and right but supposedly in Flexbox it is bad to use Floats. I was thinking about using justify-content and using flex-start and flex-end but that Isn't working out too well.

I tried applying flex-start to the first item and then flex-end to the others but that didn't work so well.

Like So:

.primary-nav #item1 {
  justify-content: flex-start;
}

.primary-nav #item2 {
  justify-content: flex-end;
}

.primary-nav #item3 {
   justify-content: flex-end; 
}

.primary-nav #item4 {
    justify-content: flex-end;    
}

Praise and thanks to anyone who has Flexbox skills and can help show me the proper way to handle this situation. :)

Answer

mmgross picture mmgross · May 31, 2015

If you're looking to have just one element on the left and all others on the right, the simplest solution is to use justify-content:flex-end on the parent element to move all elements to the right and then add margin-right:auto to the element you want to have on the left

.primary-nav {
    display:-webkit-flex;
    display:flex;
    list-style-type:none;
    padding:0;
    justify-content:flex-end;
}

.left {
    margin-right:auto;
}
<nav>
  <ul class="primary-nav">
    <li class="left"><a href="#">ListItem1</a></li>
    <li class="right"><a href="#">ListItem2</a></li>
    <li class="right"><a href="#">ListItem3</a></li>
    <li class="right"><a href="#">ListItem4</a></li>
  </ul>
</nav>