1. 水平居中
- 行内元素: text-align:center;
- 块元素: margin: 0 auto; (前提:给定宽度)
- absolute 元素:left:50%; margin-left:宽度一半的负值 (前提:给定宽度)
absolute元素的居中举例:
.header__wrap {
position: relative;
height:80px;
}
.header__logo {
position: absolute;
left: 50%;
margin-left: -200px;
width:400px;
}
2. 垂直居中
-
行内元素: line-height:height值
-
absolute元素——法1: top:50%; margin-top:高度一半的负值 (前提:给定高度)
-
absolute元素——法2: transform(-50%,-50%)
-
absolute元素——法3:top:0; right:0; bottom:0;left:0; margin:auto; (前提:给定宽高)