如何将元素水平居中 [英] How to horizontally center an element
问题描述
如何使用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>
使用 flexbox
,可以轻松地水平和垂直居中设置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>
要使div垂直居中对齐,请使用属性 align-items:center
.
To align the div vertically centered, use the property align-items: center
.
这篇关于如何将元素水平居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!