一、块级元素宽高固定
1、margin: 0 auto
当元素的width和height值固定时,使用margin可以实现元素的水平居中,无法实现元素的垂直居中
实现
div {
width: 100px;
height: 100px;
margin: 0 auto;
}
[margin: auto;元素可以水平居中,但是上下值为0]
2、position:absolute、margin负值
实现水平垂直居中
【使用relative定位无法实现元素的居中,是因为:使用该定位方式的元素没有脱离标准文档流,它的位置的偏移是根据它当前所在的文档流设置的,此时它的margin值已经失效】
【使用absolute可以实现,使用该定位方式的元素已经脱离了标准文档流,它的偏移是根据设置了除static定位方式的父元素来设置的】
实现
// margin值的设置需要我们根据元素的width和height值去计算,注意使用margin值的设置在这不能使用百分比
#parent {
position: relative;
width: 1000px;
}
div {
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
}
margin值设置为百分比时,是按照父元素的width值来设置的,所以上述情况,如果margin值设置为百分比,那么margin的取值则为-500px;并不为按照我们预想的去实现元素的水平垂直居中
二、块级元素宽高不固定
1、position:absolute/fixed、transform: translate(-50%, -50%)
实现水平垂直居中
实现
#parent {
position: relative;
width: 1000px;
}
div {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2、display:flex;
flex布局实现子元素的水平垂直居中,只要给父元素设置对应的样式即可;
无论子元素是否设置width和height值,都会水平垂直居中;
实现
#parent {
display: -webkit-flex;
display: flex;
width: 1000px;
justify-content: center;
align-items: center;
}
div {
/* 子元素无论是否设置宽高值,都会水平垂直居中 */
}
三、内联元素和文字居中
1、display:flex;
实现
#parent {
display: -webkit-flex;
display: flex;
width: 1000px;
justify-content: center;
align-items: center;
}
2、text-align: center;
实现
// 给父元素设置如下样式,内联元素不需要处理
div {
text-align: center;
}
3、display: table-cell
但这种方式IE6、7不支持,只有谷歌、火狐及IE8以上的浏览器支持
实现
// 给父元素设置如下样式,内联元素不需要处理
// vertical-align适用于表格元素
div {
display: table-cell;
text-align: center;
vertical-align: middle;
}
4、块元素中文字的垂直居中:line-height: height值
实现
// line-height的值与height的值一致,文字才会垂直居中
div {
height: 30px;
line-height: 30px;
}