Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center flex items with one at the end of the row [duplicate]

Tags:

html

css

flexbox

I am creating a navbar with flexbox. Here is my html:

<div class="container">
    <div>Project</div>
    <div>About the Project</div>
    <div>Contact Us</div>
    <div>Mailbox</div>
</div>

And my css:

.container {
  display: flex,
  justify-content: center
}

Here is what it currently looks like:

Current Navbar

I want the mailbox div to be at the end of the flex container. I want it to look more like this.

Wanted navbar

I have tried flex-end on that flex item to no avail. What do I need to do to make that happen?

like image 415
jhamm Avatar asked Feb 07 '16 06:02

jhamm


1 Answers

The layout can be achieved with flex auto margins and an invisible flex item.

.container {
  display: flex;
}
.container > div:first-child {
  margin-right: auto;
  visibility: hidden;
}
.container > div:last-child {
  margin-left: auto;
}
<div class="container">
  <div>Mailbox</div><!-- invisible flex item -->
  <div>Project</div>
  <div>About the Project</div>
  <div>Contact Us</div>
  <div>Mailbox</div>
</div>

jsFiddle

Notes:

  • Flex auto margins are used for aligning the flex items.
  • Since flexbox alignment works by distributing free space in the container, an invisible flex item is added to create equal balance on both sides.
  • It's important that the phantom item be exactly the same width as the last item (Mailbox). Otherwise, there won't be equal balance and the middle items will not be perfectly centered.

Learn more here: Methods for Aligning Flex Items

like image 126
Michael Benjamin Avatar answered Oct 24 '22 16:10

Michael Benjamin