CSS之水平居中
1.行级元素(inline元素和inline-*元素)的水平居中
在父元素中设置text-align:center;就可以使子元素中的行级元素(inline元素和inline-*元素)水平居中。行级元素包括文本、超链接等。
CSS代码:
#container{
background:#f06d06;
padding:20px 0 20px 0;
}
#header,#nav{
background:#CCC;
padding:5px 0 5px 0;
text-align:center;
}
#header{
margin-bottom:10px;
}
#nav a{
text-decoration:none;
border-radius:3px;
background:#333;
color:#fff;
padding:5px;
display:inline-block;
}
HTML代码
<div id="container">
<div id="header">
<span>This text is centered.</span>
</div>
<div id="nav">
<a href="#">One</a>
<a href="#">Two</a>
<a href="#">Three</a>
<a href="#">Four</a>
</div>
</div>
效果如图
2、单个块级元素的水平居中
2.1 margin:0 auto
使用margin:0 auto;可以使块级元素自身在父元素中水平居中。
CSS代码
#container{
background:#999;
padding:30px 0 30px 0;
}
.box{
width:400px;
height:250px;
margin:0 auto;
background:#f06d06;
}
HTML代码
<div id="container">
<div class="box">
</div>
</div>
效果如图
2.2 利用负的margin值水平居中
PS:当然利用负的margin值也可以进行垂直方向上的居中
CSS代码
#container{
background:#999;
height:600px;
position:relative;
}
.box{
width:400px;
height:250px;
position:absolute;
left:50%;
margin-left:-200px;
top:50%;
margin-top:-125px;
background:#f06d06;
}
HTML代码
<div id="container">
<div class="box">
</div>
</div>
效果如图
3、多个块级元素的水平居中
3.1 将要居中的元素设为行级元素
通过在父元素上设置text-align:center可以使子元素中display属性设置为inline-block的div水平居中
CSS代码
#container{
background:#999;
text-align:center;
padding:20px 0 20px 0;
}
#container div{
background:#f06d06;
display:inline-block;
width:250px;
padding:20px;
text-align:left;
text-indent:2em;
}
HTML代码
<div id="container">
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
</div>
效果如图
3.2 通过弹性布局设置水平居中
Flex是Flexible Box的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性。
display:flex; 弹性布局
flex-direction 决定主轴的方向(即项目的排列方向)
justify-content 定义了项目在主轴上的对齐方式
CSS代码
#container{
display:flex; /*弹性布局*/
flex-direction:row; /*主轴为水平方向,也是默认值*/
justify-content:center; /*项目在主轴上的对齐方式*/
background:#999;
padding:20px 0 20px 0;
}
#container div{
background:#f06d06;
width:250px;
padding:20px;
text-align:left;
text-indent:2em;
margin-right:20px;
}
HTML代码
<div id="container">
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
</div>
效果如图
本文参考了Chris Coyier的《Centering in CSS:A Complete Guide》和阮一峰的《Flex布局教程:语法篇》