Best way to center a `` on a page vertically and horizontally?
Effortlessly center a <div>
with CSS Flexbox. Define your container display: flex;
and use justify-content: center;
and align-items: center;
. To fill the page vertically, use a viewport height (vh
):
HTML structure:
This method is simple, responsive, and has broad support.
Absolute Positioning and Auto Margins
For a flexbox-independent solution, center a div
using absolute positioning and auto margins:
This way, thanks to auto margins, your div
will self-adjust its position, allowing for perfect centering no matter its dimensions. Note, however, that Internet Explorer 7 won't be joining this centering party, but almost all other modern browsers will.
Precise Positioning and Translation
When dealing with absolute or fixed positioned elements, transform: translate(-50%, -50%)
is your secret weapon. By translating the element back by half its width and height, it will be nicely centered no matter the screen size:
Remember to check browser support for transform
and consider implementing -webkit-transform
for those old-timer browsers.
Centering Immovable Elements
If your content needs to stay put during scrolling, simply switch position: absolute;
to position: fixed;
to create a centered but immobile element:
Just keep in mind that any layout hoping for broader support may need to rely on good old centering with fixed dimensions or even a robust JavaScript fallback.
Flexing with Flexbox
By leveraging the full power of Flexbox, you can not only center your content but potentially align every item in your layout without breaking a sweat. As long as the parent has dimensions set, child elements can have dynamically resizing backgrounds, widths, and heights:
W3Schools, MDN, and CSS-Tricks are eager to guide you through the Flexbox world.
Centering with CSS Grid
CSS Grid is another powerful tool for centering. Along with horizontal centering, it can perform vertical centering within each grid cell:
Using place-items: center;
with CSS Grid is like having a concierge for your elements, helping them find their place without needing specific sizes.
Troubleshooting centering issues
Stuck off-center? Here are some troubleshooting tips to get your content lined up properly:
- Check that parent elements aren't restricting the size or position of the centered
div
. - Make sure no flex item properties are drifting your content off-center when using Flexbox.
- For
transform
, cross-check for any CSS rules messing with your positioning commandments. - In grid layouts, ensure that your
div
is a grid item itself, and that nested grids aren't throwing spanners in your works.
Was this article helpful?