Center align content vertically and horizontally in CSS
š„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days
Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.
- šÆ Build real MVP: AI-powered SaaS from idea to launch
- š¤ Integrate ChatGPT, Claude, and other AI APIs efficiently
- š° Implement AI features users will pay for
- ā”ļø AI-assisted coding patterns to ship 10x faster
- š Launch your product in 10 days, not 10 months
Center aligning content vertically and horizontally are usual requirement in any website. There are several ways to achieve it using CSS.
- using CSS transform
- using flexbox
CSS transform
.content {
position: relative;
top: 50%;
left: 50%;
// shifts or translate the center point (X, Y) by (X - 50% of outerWidth, Y - 50% of outerHeight)
transform: translate(-50%, -50%);
}
https://codepen.io/Param-Harrison/pen/ErPyva
Limitations
- It works very well for centering content block with fixed width in both directions ā
- For non fixed width, the content block assumes 100% of parent's width. It expands the whole width of parent container horizontally. You can check this by removing width for content in codepen example ā
- this technique won't work if the content is inline level element, it only works for block level elements ā
Modern flexbox way
.parent {
display: flex;
// centering along main axis - X axis - Horizontal
justify-content: center;
// centering along cross axis - Y axis - Vertical
align-items: center;
}
https://codepen.io/Param-Harrison/pen/ZwQBxR
Note: main and cross axis depends on
flex-direction
property. By default flex-direction isrow
. If it is set ascolumn
, then main axis is Y and cross axis is X.
This approach works on almost every use cases perfectly
- fixed width of content block ā
- non fixed width of content block ā
- content can be inline level element or block level element ā
Flexbox is so powerful and you can easily develop more styles and components using it. Its supported on all major browsers, no excuse to not using it š