Table of contents
Centering an element or div can be notoriously hard sometimes, let's see some of the ways you can use to center an element or div in CSS.
1. Flexbox
<div class="center">
<p>centering is hard</p>
</div>
.center {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
Note: here we're using 'height: 100vh;' because we're centering out div in middle of screen, 100vh means full view port's height.
If you're element is inside a div/container and it has predefined height and width then you need not to use 'height: 100vh;' it'll center according to the parent width and height.
for example-
<div class="container">
<div class="center">
<p>centering is hard</p>
</div>
</div>
.container {
width: 500px;
height: 250px;
border: 5px solid black;
display: flex;
justify-content: center;
align-items: center;
}
2. Position
<div class="center">
<p>centering is hard</p>
</div>
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Note: if you want to center a div according to it's parent div then you need to give the parent div "position: relative;" because by default absolute positioning centers itself according to body.
<div class="container">
<div class="center">
<p>centering is hard</p>
</div>
</div>
.container {
width: 500px;
height: 250px;
border: 5px solid black;
position: relative;
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3. Grid
<div class="center">
<p>centering is hard</p>
</div>
.center {
height: 100vh;
/*width: auto;*/
display: grid;
place-items: center;
}
Center according to the parent div.
<div class="container">
<div class="center">
<p>centering is hard</p>
</div>
</div>
.container {
width: 500px;
height: 250px;
border: 5px solid black;
background: ghostwhite;
display: grid;
place-items: center;
}
ย