How to horizontally center a <div> in another <div>?
我怎么能水平居中一个<div>
另一个内<div>
使用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 IE8+, 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;
}
<div id="outer" style="width:100%">
<div id="inner">Foo foo</div>
</div>
如果你不想在内部div
上设置固定宽度,你可以这样做:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
The best approaches are with CSS 3.
Box model:
#outer{
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;
}
#inner{
width: 50%;
}
According to your usability you may also use the box-orient, box-flex, box-direction
properties.
Flex :
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
Read more about centering the child elements
Link 2
Link 3
Link 4
And this explains why the box model is the best approach :
上一篇: 避免!=空语句