5 Ways To Center a DIV Using CSS
Here are five different ways to center a DIV using CSS.
First of all, let's create a div in the document.
<body>
<div></div>
</body>
Then, lets make this div visible by adding width: 200px; height: 100px; and background-color: black;.
div{
width: 200px;
height: 100px;
background-color: black;
}
Now its time to center this div using these five ways:
- GRID
- FLEXBOX
- POSITION
- FLEX and MARGIN
- GRID and MARGIN
Use GRID To Center a DIV
In the parent element add display: flex; place-content: center; and height: 100vh; properties. Now your div is perfectly in the center using GRID property.
//parent element
body{
display: flex;
place-content: center;
height: 100vh;
}
Use FLEXBOX To Center a DIV
In the parent element, add display: flex; justify-content: center; and
align-items: center; and height: 100vh; properties. Now the DIV is again in the center.
//parent element
body{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Use POSITION To Center a DIV
In the child element, add position: absolute; top: 50%; left: 50% and transform: translate(-50%,-50%);. The DIV is in the center using the POSITION property.
//child element
div{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 100px;
background-color: black;
}
Use FLEX and MARGIN To Center a DIV
In the parent element, add display: flex; and height: 100vh;. And then in the child element, add margin: auto;. The DIV is in the center using only FLEX and MARGIN.
//parent element
body{
display: flex;
height: 100vh;
}
//child element
div{
margin: auto;
width: 200px;
height: 100px;
background-color: black;
}
Use GRID and MARGIN To Center a DIV
In the parent element, add display: grid; and height: 100vh;. Then in the child element, add margin: auto;. The DIV is in the center.
//parent element
body{
display: grid;
height: 100vh;
}
//child element
div{
margin: auto;
}