CSS: Pushing a Menu Item to the right

by||2 min read

A common scenario is a header bar with some items aligned to the left and some items aligned to the right. What I usually used to do is placing an empty element with flex-grow between the left and the right container:

<div class="flex flex-row">
  <div>Menu Item 1 (left aligned)</div>
  <div>Menu Item 2 (left aligned)</div>
  <div class="flex-grow"></div>
  <div>
    Menu Item 3 (right aligned)
  </div>
</div>

There is nothing wrong with this solution. As you can see - I used Tailwind CSS to create a container div for our menu. Thanks to Flexbox set to row the inner items will be on one line, by default aligned to the left (start). By placing an extra empty div element with the flex-grow: 1 (flex-grow in TailwindCSS) we can push the following element to the right. This item is a helper which does not take a lot of space in our HTML but still pollutes it in a way.

Pushing an Element to the right without helper HTML

In fact, there is another way to achieve the same result without using a helper element. We just need to set the margin-left property of our right item to auto, like this:

<div class="flex flex-row">
  <div>Menu Item 1 (left aligned)</div>
  <div>Menu Item 2 (left aligned)</div>
  <div class="ml-auto">
    Menu Item 3 (right aligned)
  </div>
</div>

The ml-auto class in Tailwind will do exactly this, it sets the margin-left to auto. This way the element will "automagically" fill up the space to the left with its preceding siblings. Et voila! No extra element anymore!

Bonus

The same trick works as well with the orientation of flex-col (float elements into one column) in combination of mt-auto (margin-top: auto). This way we can "push" a single element to the bottom:

<div class="flex flex-col">
  <div>Some text at the top</div>
  <div>More text on the top</div>
  <div class="mt-auto">
    Item pushed to the bottom
  </div>
</div>

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

© Copyright 2022 - Ersocon - All rights reservedVer. 2.3.6.9