Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to align an item to the right

Short answer

In a flex row margin-left: auto takes all the free space to the left of the item and pushes it to the right:

<nav style="display: flex; gap: 12px; padding: 8px; background: whitesmoke;">
  <a href="https://example.com">Home</a>
  <a href="https://example.com">Blog</a>
  <a href="https://example.com" style="margin-left: auto;">Log in</a>
</nav>

Everything after such an item also moves to the right — handy for a header with a logo on the left and buttons on the right.

All items to the right

justify-content: flex-end moves the whole group to the right:

<div style="display: flex; justify-content: flex-end; gap: 8px;">
  <button>Cancel</button><button>Save</button>
</div>

A block without flexbox

A block with a set width only needs margin-left: auto, and text-align: right aligns text and inline elements:

<div style="width: 160px; margin-left: auto; padding: 8px; background: lavender;">Block on the right</div>
<p style="text-align: right;">Text on the right</p>

Common mistake

float: right is no longer needed for this: it takes the element out of the flow, the nearby text starts wrapping around it, and the parent can collapse. Use flexbox for buttons and menus.

Functions used in this recipe

  • margin — The outer spacing of an element — the distance to its neighbors.
  • justify-content — Distributes items along the main axis of a flex or grid container.
  • text-align — Horizontal alignment of text and inline content inside a block.

Thanks for reading!

Donate to the site — we work hard for you.