Different Ways to center a div
imagine yourself doing this to center a div ! 🤣
To avoid this, here are three different ways to center a div. Therefore, you can play the teacher’s role and teach your friends how to center a div 😎
1 — using position and transform 🧘
One of the simplest ways to center a div is by using position and transform CSS properties, but how ?
observe the code below :
<!-- HTML code -->
<div class="container">
<div class="target-dev"></div>
</div><!-- CSS code -->* {
padding : 0;
margin : 0;
box-sizing : border-box;
}.container {
height : 100vh;
width : 100vw;
position: relative; /*parent element*/
}.target-dev {
border: solid 1px lightgreen;
height : 400px;
width : 400px;
position : absolute; /*next four lines for child element*/
top : 50%;
left : 50%;
transform : translate(-50% , -50%);
}
2. using flexbox 🤖
flexbox is a powerful CSS layout module that gives web designers and developers an efficient and simple way to lay out, align and distribute elements in a container. Therefore, it provides a great way to center a div (elements)
HTML code 👇
<div class="container">
<div class="target-dev"></div>
</div>
CSS code 👇
* {
padding : 0;
margin : 0;
box-sizing : border-box;
}
.container {
height : 100vh;
width : 100vw;
display : flex; /*next Three line for parent element*/
justify-content: center;
align-items : center;
}
.target-dev {
height : 400px;
width : 400px;
border: solid 1px lightgreen;
}
3. using grid system 🖥️
CSS grid layout or CSS grid creates complex responsive web design grid layouts more easily and consistently across browsers. And I highly recommend learning Grid it will make your life more easier
“It is a shame for a developer to grow old without seeing the beauty and strength of which grid system is capable.” by a wise man
Now let’s center our div using grid 😍
HTML code 👇
<div class="container">
<div class="target-dev"></div>
</div>
Css code 👇
* {
padding : 0;
margin : 0;
box-sizing : border-box;
}
.container {
height : 100vh;
width : 100vw;
display : grid; /*next two line for parent element*/
place-content : center;
}
.target-dev {
height : 400px;
width : 400px;
border: solid 1px lightgreen;
}
conclusion
Thanks for reading❤️ , your advices and suggestions are welcome