Different Ways 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)

<div class="container">
<div class="target-dev"></div>
</div>

* {
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

<div class="container">
<div class="target-dev"></div>
</div>
* {
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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abdelmalek Ennani

Abdelmalek Ennani

👨‍💻 Software engineering student 🔥 JavaScript lover ☕ ReactJs 👩‍🔧 @redux/toolkit react-refux 🧠 Laravel tinker 🔥