jhamm jhamm - 5 months ago 10
CSS Question

Center flex items with one at the end of the row

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?

Answer

Because flexbox does not provide a justify-self property, the desired layout can be achieved with auto margins and an invisible flex item.

HTML

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

CSS

.container { display: flex; }

.container > div:first-child { margin-right: auto; visibility: hidden; }

.container > div:last-child { margin-left: auto; }

DEMO

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