How to align a <div>
to the middle (horizontally/width) of the page
Get your div
centered like a pro with this speedy snippet of CSS:
Apply the .centered
class to your div like so:
This CSS magic trick, a.k.a margin: 0 auto;
, sets equal left and right margins, essentially air-lifting your div to the middle of its container.
Navigating the fixed width airspace
In times when your div
is playing it safe with a fixed width, like 800px
, margin: 0 auto;
is your trusty compass. Don't forget, width declaration is a must - it's your div's seat belt against unexpected stretching:
Warning: Turbulence ahead with fixed widths during responsive design – media queries might come in handy for different screen sizes.
Advanced auto-pilot centering
Sometimes you need to break free from formatting shackles and see your div
soar sky-high in absolute positioning paradise. Employ the dynamic duo: transform
and position: absolute;
, for near-perfect element centering:
Behold, your div, bravely maintaining center amidst the whirlwind of resizing browser windows.
Flexbox – your div's First Class ticket
Craving for horizontality? Flexbox has a window seat with your div’s name on it. For luxuriously easy layouts, remember this mantra – display: flex; justify-content: center;
:
With Flexbox, your div will always be in the lap of luxurious alignment and beautiful spacing. Sit back, and enjoy the smooth flight with unmatched browser compatibility.
Inline elements - an exception to auto margins
When auto margins don’t play ball with inline or inline-block elements, show them who’s boss with the good ol’ text-align: center;
:
Handling the extravaganza of overflowing content
When your div is attired in its full-width costume, a savior on a white horse in the form of transform
, combined with negative translate values, will ensure your div steals the limelight, even when it's overflowing the stage:
Cruise control with container queries
Rediscover the joy of centering as you travel with old companions like display: table;
and display: table-cell;
combined with vertical-align: middle;
:
Old-school, yet timeless, like a vintage Cadillac.
Was this article helpful?