4 Easy ways to center a .div.

4 Easy ways to center a .div.

·

3 min read

Featured on daily.dev

We've all been there, that dreaded moment in a developer's life where they're asked to center a div... What do you do? How can you do it? CSS can be so hard!

Lucky for you my friend, i'm here to give you 4 easy ways of centering a div! We'll be centering our child element.

This is our HTML document

<div class="parentElement">
  <div class="childElement"></div>
</div>

And our basic CSS

.parentElement {
  width: 300px;
  height: 300px;
  background-color: rgb(128, 128, 128);
}

.childElement {
  width: 100px;
  height: 100px;
  background-color: rgb(52, 54, 97);;
}

It should look like this:

Screenshot (147)

Now let's begin!!!

Using CSS Grid

I know, i know, using CSS Grid is everything but easy... just hear me out!

We have to add grid to our parent element and a way for it to justify(horizontal) and align(vertical) our content.

.parentElement {
  display: grid; 
  justify-content: center;
  align-content: center;

And it should be looking like this:

Screenshot (148)

That's it!! We have succesfully centered our child element !!

Let's move to the second way of centering a .div!

Using Flexbox

Now, we need to add the same properties we did for our grid but, setting the display to the model flexbox.

.parentElement {
  display: flex; 
  justify-content: center;
  align-content: center; 
}

And here it is! Screenshot (148) Lovely, isn't it?

We have 2 easy ways to go! Let's continue.

Using Margin

We can center a .div using margin:auto in our flex item!! This will center it both vertically and horizontally.

.parentElement {
display: flex;
}

.childElement {
margin: auto;
}

Screenshot (148) There you have it!

Now off to the last one!

Using the position property

This one requires a few more lines of code, but don't worry! It's still an easy way.

We first need to set the position of our parent element to relative, followed by our child element position to absolute while also setting transform, top, left and right properties. To learn more on relative, absolute and fixed position click me!

.parentElement {
position: relative;
}

.childElement {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

Screenshot (148)

That is all! You've made it, friend! Now you have 4 ways to center a div at your disposal.


As always thank you SOOO much for reading!! :)

I really hope you learned something new today!

Don't hesitate to contact me and let me know what you think in the comments!

☕If you enjoy my content Buy me a coffee It'll help me continue making quality blogs💕

💙Follow me on Twitter to know more about my self-taught journey!

💜Make sure to check out more articles on my Web Design for Beginners Series

💜And if interested check out more articles on my JavaScript For Newbies Series

❤️ Also subscribe to my Youtube Channel !

🖤And for more content and tips on TikTok !