CSS HTML

How to horizontally center a div inside another?

February 5, 2022

How to horizontally center a div inside another?

In this article you will learn once and for all how to horizontally center one div inside another in your HTML page with CSS

In this article you will learn once and for all how to horizontally center one div inside another in your HTML page with CSS cover

Hey you programmer, how are you? Let’s learn more about HTML and CSS!

We can center a div inside another in several ways

What will determine which one you choose is your design.

So let’s see each of them with practical examples

Margin auto

This is the easiest way to center a div, when you add a width to the child div it automatically goes to the left

Adding margins with automatic value you center it in the main container, see it running:

<div class="container">
 <div class="child"></div>
</div>

Now the CSS:

.container {
 background-color: blue;
 width: 100%;
 height: 200px;
}

.child {
 background-color: red;
 width: 50px;
 height: 50px;
 margin: auto;
}

And the final result is:

With Absolute Position

The idea here is to center by position with a value of absolute, for this the parent must have a relative position, as it will be where the child div will be based to center

Let’s see in practice the CSS, because the HTML can be the same:

.container {
 background-color: blue;
 width: 100%;
 height: 200px;
 position: relative;
}

.child {
 background-color: red;
 width: 50px;
 height: 50px;
 position: absolute;
 left: 50%;
 margin-left: -25px;
}

Here, in addition to the absolute position, we add a left of 50%, which takes the div to 50% of the width of the parent container

But it will be misaligned, the reference is always the beginning

So we fixed that with margin-left subtracting half the width of this div, then it is centered, see the example:

Flexbox

We can also centralize with flexbox, it’s even easier

Take a look:

.container {
 background-color: blue;
 width: 100%;
 height: 200px;
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
 justify-content: center;
}

.child {
 background-color: red;
 width: 50px;
 height: 50px;
}

The final result will be the same:

Conclusion

In this article we learned  how to horizontally center a div inside another

We use several methods: margin auto, position absolute to flexbox

You just have to choose which one best fits your project!

Wanna learn more about CSS? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x