如何水平居中元素 [英] How to horizontally center an element
问题描述
如何使用 CSS 将
中?<div id="inner">Foo foo</div>
解决方案 您可以将此 CSS 应用到内部
:#inner {宽度:50%;边距:0 自动;}
当然,您不必将width
设置为50%
.任何小于包含
的宽度都可以使用.margin: 0 auto
是实际居中的内容.如果您的目标是 Internet Explorer 8(及更高版本),最好有相反:
#inner {显示:表;边距:0 自动;}
它将使内部元素水平居中,并且无需设置特定的width
.
这里的工作示例:
#inner {显示:表;边距:0 自动;边框:1px纯黑色;}#外{边框:1px纯红色;宽度:100%}
<div id="inner">Foo foo</div>
编辑
使用 flexbox
可以很容易地为 div 设置水平和垂直居中的样式.
#inner {边框:1px纯黑色;}#外{边框:1px纯红色;宽度:100%;显示:弹性;对齐内容:居中;}
<div id="inner">Foo foo</div>
要将 div 垂直居中对齐,请使用属性 align-items: center
.
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>
EDIT
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
.
这篇关于如何水平居中元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文