5 Simple Ways To Horizontally Center The DIV
Are you struggling with the horizontal alignment of the element and wanna horizontally center the div?
The ultimate goal
By using width and margin
If you can give width to the element then you can set the left and right margin auto. And it is compatible with all browsers.
.parentDiv { border: 1px solid red; } .childDiv { border: 1px solid green; width: 40%; margin-left: auto; margin-right: auto; }
<div class="parentDiv"> <div class="childDiv">Child Div</div> </div>
By using display table
If you don’t know the width of the element then you can use display table and left, right margin auto as given in the example below.
.parentDiv { border: 1px solid red; } .childDiv { border: 1px solid green; display: table; margin-left: auto; margin-right: auto; }
<div class="parentDiv"> <div class="childDiv">Child Div</div> </div>
Some time it is required to check the browser compatibility of the css property, for that you can use caniuse
By using display inline-block
Inline-block allows the element to use inline as well as block-level capabilities. Like text-align center is an inline-level property.
As we defined the element as inline-block it will be no longer a full-width element, now it will just cover the content. So, here text-align comes in the picture and make the element center.
.parentDiv { border: 1px solid red; text-align: center; } .childDiv { border: 1px solid green; display: inline-block; }
<div class="parentDiv"> <div class="childDiv">Child Div</div> </div>
By using display flex
Flexbox is always my favourite and as the name suggests it is too much flexible in terms of alignment.
Here I am just using horizontal alignment but there is much more with flexbox and will talk in another article.
.parentDiv { border: 1px solid red; display: flex; justify-content: center; } .childDiv { border: 1px solid green; width: 40%; }
<div class="parentDiv"> <div class="childDiv">Child Div</div> </div>
By using offset properties
Where you don’t know the actual width of the element you can set left 50% and 50% translate the element horizontally.
Note: offset properties like left, right, top and bottom can work only in the presence of position other than static (default)
.parentDiv { border: 1px solid red; position: relative; } .childDiv { border: 1px solid green; position: relative; width: 60%; left: 50%; transform: translateX(-50%); }
<div class="parentDiv"> <div class="childDiv">Child Div</div> </div>
Ok, done.
By the way, go and check out my JavaScript articles also.
You are most welcome to share your opinion about this post, not only this post but about the whole blog. Please do comment below in the comment section.
Great content! Super high-quality! Keep it up! 🙂