Sometimes we need to horizontally center a div that is within another div using CSS that make the inner element center horizontally.
In that case, you don’t have to set the width to 50%. So, any width which is less than the containing div will work.
For example, you have the following HTML:
<div id="outerDiv" style="width: 100%"> <div id="innerDiv">Content goes here...</div> </div>
Apply this CSS to the inner div:
#innerDiv {
width: 50%;
margin: 0 auto;
}
The margin: 0 auto is what does the actual centering.
#outerDiv {
width: 100%;
text-align: center;
}
That makes the inner div centered with text-align.
Read Also: Align text vertically next to an image
If you are targeting IE8+, then you can use this instead:
#innerDiv {
display: table;
margin: 0 auto;
}
This will make the inner element center horizontally without setting a specific width.
#outerDiv{
width:100%;
/* Firefox */display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari and Chrome */display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */display:box;
box-pack:center;
box-align:center;
}
#innerDiv{
width:50%;
}
If you are targeting IE8+, this might be better to have this instead:
#innerDiv {
display: table;
margin: 0 auto;
}
This will make the inner element center horizontally and this works also without setting a specific width.
Let’s face it. Tech buzzwords get thrown around a lot—especially when it comes to how…
In today’s digital world, the boundaries between technology, finance, and innovation are rapidly disappearing. Businesses…
Backyard gatherings like BBQs, family reunions, and garden parties are an exciting way to enjoy…
Marketers are always on the lookout for more effective ways to reach their target audiences.…
Does your phone control your mind more than you control your phone? Modern life exploits…
Did you know that the prostate continues growing throughout a man's entire life, making BPH…