How to Center a Div : CSS Tips and Tricks
Centering a div on a web page can sometimes be challenging, especially for beginners in web development. However, there are several ways to do this using CSS. In this article, we will discuss five common methods to center a div, along with their respective code examples.
We can center a div :
- Using position
- Using flexbox
- Using flex & margin
- Using grid
- Using grid & margin
→ Note:- Here I am giving main-div and sub-div codes in different code blocks so that you can learn them easily and in a proper way. First copy the first code block to see the effect and then move to the second one.
1. Using position
The first method is by using the position property. In this method, we set the position of the parent div to relative and the child div to absolute. Then, we use the top, left, and transform properties to center the child div within the parent div.
.main-div{
position: relative;
}
.sub-div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
2. Using flexbox
The second method is by using the display property with the value flex. We set the justify-content and align-items properties to center the child div both horizontally and vertically within the parent div.
.main-div{
display: flex;
justify-content: center;
align-items: center;
}
3. Using flex & margin
The third method is also using the display property with the value flex, but instead of using the justify-content and align-items properties, we use the margin property to center the child div within the parent div.
.main-div{
display: flex;
}
.sub-div {
margin: auto;
}
4. Using Grid
The fourth method is by using the display property with the value grid. We set the place-content property to center the child div within the parent div.
.main-div{
display: grid;
place-content: center;
}
5. Using grid & margin
The fifth method is also using the display property with the value grid, but instead of using the place-content property, we use the margin property to center the child div within the parent div.
.main-div{
display: grid;
}
.sub-div {
margin: auto;
}
Conclusion :
In conclusion, there are multiple ways to center a div using CSS, and each method has its own advantages and disadvantages. As a web developer, it is essential to understand these methods and choose the best one based on the project’s requirements. We hope this article helps you to understand the most common ways to center a div on a web page using CSS.