如何水平放置< div>居中? [英] How to horizontally center a <div>?
问题描述
如何使用CSS将<div>
在另一个<div>
中的水平居中位置?
How can I horizontally center a <div>
within another <div>
using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
推荐答案
您可以将此CSS应用于内部<div>
:
You can apply this CSS to the inner <div>
:
#inner {
width: 50%;
margin: 0 auto;
}
当然,您不必将width
设置为50%
.小于包含的<div>
的任何宽度都将起作用. 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.
如果您定位到 Internet Explorer 8 (及更高版本),则最好设置而是:
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
它将使内部元素水平居中,并且无需设置特定的width
即可工作.
It will make the inner element center horizontally and it works without setting a specific width
.
此处的工作示例:
#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>
使用flex-box
,可以轻松地水平和垂直居中设置div的样式.
With flex-box
, 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>
要同时使div垂直居中对齐,请使用属性align-items: center
.
To align the div vertically centered also, use property align-items: center
.
这篇关于如何水平放置< div>居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!