Explain Codes LogoExplain Codes Logo

How do I right align div elements?

html
responsive-design
css
flexbox
Nikita BarsukovbyNikita Barsukov·Nov 6, 2024
TLDR

To right-align divs, leverage the power of flexbox. Apply display: flex; and justify-content: flex-end; to the parent container:

.container { display: flex; justify-content: flex-end; /* No div left behind */ }

Now, place your div in the container and let the magic happen:

<div class="container"> <div>I live on the right now</div> </div>

This nudges the div to the far-right edge in a snappy, responsive manner.

Beyond the basics

Shifting unwanted space with flex-grow

Within a flex container, the flex-grow property comes in handy. It swallows additional space and pushes div elements to the right

.child { flex-grow: 1; /* I'm a space vacuum */ }

Handling the sibling rivalry (stacking)

For multiple divs, use flex-wrap: wrap; to prevent sibling divs from invading each other's space:

.container { display: flex; flex-wrap: wrap; /* Sibling rivalry no more! */ } .child { margin-left: auto; /* Moving to the right felt right */ }

Responsive solution with flexbox

Flexbox also does a remarkable job when it comes to dynamic width and responsive design.

.container { display: flex; } .child { flex: 1 1 auto; /* Who said I'm not flexible? */ min-width: 0; /* Dropping the weight */ }

Right-align divs without flex

Flexbox not your cup of tea? Worry not, there's more than one way to skin a cat.

Inline-block with text-align

.container { text-align: right; /* Because right feels right */ } .child { display: inline-block; /* Standing in line feels divine */ }

Auto margin magic

.child { margin-left: auto; /* Scoot over to the right */ margin-right: 0; /* Getting cozy with the right edge */ }

Overflow handling for the float fans

For those who love floats, handle overflow issues using a clear-fix:

.container::after { content: ""; display: table; clear: both; /* Overflow? Overruled! */ }

Other alignment techniques

Positioning to the rescue

Absolutely positioned elements can be placed right:

.child { position: absolute; right: 0; /* Right is right, right? */ }

Evenly spacing items

For an evenly distributed layout, justify-content: space-around; is your friend:

.container { display: flex; justify-content: space-around; /* Sharing is caring */ }

Handling IE blues

Cater for IE-related issues with these quick tips:

  • Be aware of the IE Double Margin Bug
  • Use display: table-cell; and vertical-align: middle; for vertical centering when flexbox isn't acceptable
  • Substitute flex with display: inline-block; and text-align: right; to align divs on older IE versions