水平居中
1. text-align:center
父元素下的所有行级元素,包含子元素以及孙子元素,都相对于自己的父元素水平居中。
.parent{
text-align:center;
}
2. margin:0 auto
只有非绝对定位的元素才有效。 绝对定位的:absolute和fixed。 其他定位:inherit、initial、unset、revert、relative、sticky、static。
.parent{
margin:0 auto;
}
3. flex布局
.parent{
display:flex;
justify-content:center;
}
4. 盒模型display:box
.parent{
display: box;
box-orient: horizontal;
box-pack: center;
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: center;
display: -o-box;
-o-box-orient: horizontal;
-o-box-pack: center;
display: -ms-box;
-ms-box-orient: horizontal;
-ms-box-pack: center;
}
5. 绝对定位
(1) 绝对定位+margin
.son{
position:absolute;
left:0;
right:0;
margin:0 auto;
}
(2) 绝对定位+transform
.son{
position:absolute;
left:50%;// 相对于父元素width的50%
transform:translate(-50%,0);// 相对于自身的width
}
(3) 绝对定位+margin-left
// 注意:子元素的宽度要已知
.son{
width:200px;
position:absolute;
left:50%;
margin-left:-100px;
}
垂直居中
1. 单行文本
.son{
line-heignt:父元素的高度;
}
2. vertical-align:center
(1) 行级块元素display:inline-block;
.son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
display:inline-block;
vertical-align:middle;
}
(2) display:table
.parent{
display:table;
}
.son{
display:table-cell;
vertical-align:middle;
}
3. flex布局
.parent {
display: flex;
align-items: center;
}
4. 盒模型didsplay:box
.parent {
display: box;
box-orient: vertical;
box-pack: center;
}
绝对定位
(1) transform
.son{
position:absolute;
top:50%;
-webkit-transform: translate(0,-50%);
-ms-transform: translate(0,-50%);
transform: translate(0,-50%);
}
(2) margin-top
.son{
position:absolute;
top:50%;
height:固定;
margin-top:-0.5高度;
}
(3)margin:auto 0;
.son{
position:absolute;
height:固定;
top:0;
bottom:0;
margin:auto 0;
}