Centering a div vertically and horizontally on a web page is a common task in web design. However, achieving the perfect alignment can be a frustrating experience. In this article, we explore four different techniques for centering a div with CSS. Whether you’re a beginner or an experienced developer, you’re sure to find a technique that works for you or at least get reminded which solutions work best for your situation.
Using Flexbox
The first technique uses CSS flexbox, a powerful layout system that makes it easy to align items both horizontally and vertically. To center a div you need to set the parent container to display:flex
and then use the justify-content
and align-items
properties to center the child element. This is probably the most commonly used solution nowadays.
.parent {
display: flex;
justify-content: center;
align-items: center;
}
Using Grid
The second technique uses CSS grid, another powerful layout system that lets you create complex layouts with ease. To center a div with grid you need to set the parent container to display:grid
and then use the justify-content
and align-items
properties to center the child element. Quite similar to the flexbox solution as you see.
.parent {
display: grid;
justify-content: center;
align-items: center;
}
.child {
width: 300px;
height: 200px;
}
Using Position
The third technique uses the position property to center a div. Set the parent container to position:relative
and then set the child element to position:absolute
with top
, bottom
, left
and right
values set to 0.
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
Using Transform
The fourth technique uses the transform property to center a div, it’s a classic by now. You need to set the parent container to position:relative
and then set the child element to position:absolute
with top
and left
values set to 50%
. You then use the translate
property to move the child element back by 50%
of its own width
and height
. Here’s an example:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
height: 200px;
}
Conclusion
There are different ways to center a div
with CSS. Each technique has its strengths and weaknesses, so it’s up to you to choose the one that works best for your specific situation. Whether you use flexbox, grid, position or transform, you can rest assured that you’ll be able to create perfectly centered divs with ease.