How do you easily horizontally center a `` using CSS?
To center a <div>
horizontally using CSS, simply give it a proper width
and set both margin-left
and margin-right
to auto
:
Use this class in your <div>
:
This quick trick often does the job for block elements with a fixed width.
Centering strategies for more complex cases
Inline-block for unpredictable content width {
Dealing with dynamic content? Use display: inline-block
to keep it centered:
Then wrap your <div>
with a parent div
:
Legacy browser hacks
If you're dealing with IE6 (yes, it's a dinosaur but some still use it), use a <div>
wrapper:
Flexbox comes to the rescue
Here's how to use Flexbox and come off like a pro:
And in your HTML:
The Transformer way
Last but not least, for exceptional precision, use a CSS transform
:
The transform method becomes helpful when width varies and 'adapting to content' is your mantra.
Extra tips and tricks to make it even better
Min-width for flexible stability
You can use min-width
to prevent the <div>
from becoming too wimpy, while melting hearts with a stable yet flexible layout. Browser support is a must-check, though.
Making things visible with background color
Light up the development stage with background-color: #eee;
on your <div>
as it works like a superstar on Broadway, making layout issues easier to spot.
Class act for the maintenance team
Cook up a specific class (let's say .centered
) for your centering styles. This keeps your CSS squeaky clean and easy to maintain, and inline styles on a diet.
HTML5/CSS3 treats, but with mindfulness
Always remember to include polyfills for HTML5/CSS3 features and do a rain dance praying older browsers support it. Double-check the need for vendor prefixes with properties like transform
.
Responsive approach with vw
Come across as a genius with responsive units like vw
(viewport width). Let your design sip on this responsive potion for fluid centering, but be careful not to spill it over on smaller screens!
Was this article helpful?