5 ways to center a div using CSS.
Let me tell you about a guy named Chandler. Chandler was an excellent programmer. He used to write clean and decoupled code. He used to architecture robust and extensible design systems. He was loved by all.
One day, he wanted to center a div, and everything changed for him…
Honestly, we all struggle with CSS and try to find our peace with it. We’ve all found ourselves frustrated with centering things in CSS.
Allow me to quickly tell you 5 ways by which you can center a div vertically and horizontally —
Problem statement
We have 2 divs parent
and child
and we need to center child
with respect to the parent
.
<div class="parent">
<div class="child"></div>
</div>
1. Using Flexbox
The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.
Applying following properties to .parent
will center .child
horizontally and vertically.
.parent {
display: flex;
justify-content: center;
align-items: center;
}
Complete code:
2. Using Position
The position
property specifies the type of positioning method used for an element (static, relative, fixed, absolute or sticky).
Apply position relative
to .parent
:
.parent {
position: relative;
}
To .child
div, apply position absolute
and center the content using top
, left
and transform
properties:
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Complete code:
3. Using CSS grid
The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning.
Applying following properties to .parent
will center .child
horizontally and vertically.
.parent {
display: grid;
justify-content: center; /*horizontal*/
align-content: center; /*vertical*/
}
Complete code:
4. Using Tables
There was a time when tables were the only real way to structure HTML, namely the syntax. But using CSS styling, we can make elements, such as <div>
tags behave like <table>
and <td>
tags.
Apply following properties to .parent
.parent {
display: table-cell;
text-align: center; /*horizontal*/
vertical-align: middle; /*vertical*/
}
Apply following property to .child
.child {
display: inline-block;
}
Complete code:
5. Margin auto on a flex item
Using margin: auto
on a flex item will not only horizontally center the element as it did in block layouts, but also center it in the vertical axis:
Apply following properties on .parent
and .child
:
.parent {
display: flex;
}.child {
margin:auto;
}
Complete code:
Level Up Coding
Thanks for being a part of our community! Subscribe to our YouTube channel or join the Skilled.dev coding interview course.