如何在 Flexbox 中垂直和水平居中元素
以下是两种通用的定心解决方案。
一个用于垂直对齐的弹性项目 (flex-direction: column),另一个用于水平对齐的弹性项目 (flex-direction: row)。
在这两种情况下,居中 div 的高度可以是可变的、未定义的、未知的,等等。居中 div 的高度无关紧要。
这是两者的 HTML:
<div id="container"><!-- flex container -->
<div class="box" id="bluebox"><!-- flex item -->
<p>DIV #1</p>
</div>
<div class="box" id="redbox"><!-- flex item -->
<p>DIV #2</p>
</div>
</div>
CSS(不包括装饰样式)
当弹性项目垂直堆叠时:
#container {
display: flex; /* establish flex container */
flex-direction: column; /* make main axis vertical */
justify-content: center; /* center items vertically, in this case */
align-items: center; /* center items horizontally, in this case */
height: 300px;
}
.box {
width: 300px;
margin: 5px;
text-align: center; /* will center text in <p>, which is not a flex item */
}
DEMO
当弹性项目水平堆叠时:
调整以上代码中的flex-direction 规则。
#container {
display: flex;
flex-direction: row; /* make main axis horizontal (default setting) */
justify-content: center; /* center items horizontally, in this case */
align-items: center; /* center items vertically, in this case */
height: 300px;
}
DEMO
使弹性项目的内容居中
flex formatting context 的范围仅限于父子关系。子元素之外的 flex 容器的后代不参与 flex 布局,并且会忽略 flex 属性。本质上,flex 属性不能被子级继承。
因此,您始终需要将 display: flex 或 display: inline-flex 应用于父元素,以便将 flex 属性应用于子元素。
为了使弹性项目中包含的文本或其他内容垂直和/或水平居中,请将项目设为(嵌套)弹性容器,并重复居中规则。
.box {
display: flex;
justify-content: center;
align-items: center; /* for single line flex container */
align-content: center; /* for multi-line flex container */
}
更多详情:How to vertically align text inside a flexbox?
或者,您可以将margin: auto 应用于弹性项目的内容元素。
p { margin: auto; }
在此处了解 flex auto 边距:Methods for Aligning Flex Items(参见框#56)。
使多行 flex 项居中
当 flex 容器有多行(由于换行)时,align-content 属性将是横轴对齐所必需的。
来自规范:
8.4. Packing Flex Lines: the align-content
property
align-content 属性在
当横轴有额外空间时,弹性容器,类似于
justify-content 如何在主轴内对齐单个项目。
请注意,此属性对单行 flex 容器没有影响。
更多详情:How does flex-wrap work with align-self, align-items and align-content?
浏览器支持
所有主流浏览器都支持 Flexbox,except IE < 10。一些最新的浏览器版本,例如 Safari 8 和 IE10,需要vendor prefixes。要快速添加前缀,请使用Autoprefixer。更多详情this answer。
针对旧版浏览器的居中解决方案
有关使用 CSS 表格和定位属性的替代居中解决方案,请参阅此答案:https://stackoverflow.com/a/31977476/3597276