How can I horizontally center a <div>
within another <div>
using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
You can apply this CSS to the inner <div>
:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width
to 50%
. Any width less than the containing <div>
will work. The margin: 0 auto
is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width
.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
With flexbox
it is very easy to style the div horizontally and vertically centered.
#inner {
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
To align the div vertically centered, use the property align-items: center
.
For the vertical centering I usually use "line-height" (line-height == height). This is simple and nice but it's only working with a one line content text :)
You have to use the !DOCTYPE tag on your html page to make it work well on IE.
Note that it may be necessary to add "float:none;" for the #inner.
You also set the top and bottom margins to 0, which is unrelated. Better putting
margin-left: auto; margin-right: auto
I think.Not necessarily
margin:0 auto
: it can bemargin: <whatever_vertical_margin_you_need> auto
second being the horizontal margin.