CSS
Best 3 Ways to Center a Div with CSS
A beginner person always faces the problem of center div on a webpage.
I’m Face lots of trouble maybe you also. When I center div in the web page, one browser center div properly, and other browsers do not properly work. That reason CSS is very confusing for beginner people. You try some other CSS property to center div. But you fail.
In This article, we cover the top three ways to center div with CSS. We do not use any advanced CSS. We only use basic CSS property to center div.
Let’s start it.
- First ways
- Second ways
- Third ways
First ways
Firstly, we use the CSS position property. which is a common way to center div in CSS. Lots of time, I use position property to center div. this is a very easy and old technique to center div.
HTML code
<div class="center">
CSS code
.center{
position: absolute;
top:50%;
left: 50%;
transform: translate(-50% , -50%)
}
Demo
Second ways
secondly, we use flexbox to center div in a web browser. Flexbox functionally helps to center div very easily. These are new ways to center div as compare first ways.
Flexbox design a one-dimensional layout in your browser. Bootstrap also uses flexbox property to center div in a web browser.
HTML code
<div class="flex">
<div class="center" > </div>
</div>
CSS code
.flex{
display: flex;
align-items:center;
justify-content: center;
}/* center class for add style in div */.center{
background-color: black;
width:250px;
height: 250px;
}
Demo
Third ways
Thirdly, we use a grid layout to center div in the web browser. Grid layout new ways to center your div. the grid system is very cool and easy to use. The grid system very effectively designs a 3D website layout. I'm also recommended to use a grid system in the website rather than use any CSS framework.
HTML code
<div class="grid">
<div class="center" > </div>
</div>
CSS code
.grid{
display: grid;
place-items:center;
}/* center class for add style in inner div */.center{
background-color: black;
width:250px;
height: 250px;
}
Demo
Reference
Conclusion
Many ways use to center your div in a web browser. In this article, I'm covering only the common method in CSS. If you are interested to learn more related to center div. then follow my reference article and also follow StackOverflow