# 如何实现居中
# 水平垂直居中
知道元素宽高:
- 利用定位 + margin:负值(不要求父元素的高度),设置父元素为相对定位, 子元素移动自身50%
<style>
.father {
position: relative;
width: 200px;
height: 200px;
}
.son {
position: absolute;
top: 50%;
left: 50%;
margin-left:-50px;
margin-top:-50px;
width: 100px;
height: 100px;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- table布局
<style>
.father {
/*img标签也可这么用*/
display: table-cell;
width: 200px;
height: 200px;
background: skyblue;
vertical-align: middle;
text-align: center;
}
.son {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
不需要知道元素宽高:
- 利用定位absolute + margin:auto + top:0 + left:0
- 利用定位absolute + transform: translate(-50%,-50%) + top:50% + left:50%
- flex布局:flex-direction flex-wrap justify-content align-items
- grid布局:grid-template-colums/rows(每行每列分份) grid-area(给item命名)
# 水平居中
- 行内元素可设置:text-align: center (内联元素)
- flex布局设置父元素:display: flex; justify-content: center(内联元素)
- 定宽: margin: 0 auto(块级元素)
- 绝对定位+left:50%+margin:负自身一半(块级元素)
# 垂直居中
- 单行文本父元素确认高度:height === line-height(内联元素)
- 多行文本父元素确认高度:display: table-cell; vertical-align: middle(内联元素)
- position: absolute设置left、top、margin-left、margin-top(定高)(块级元素)
- display: table-cell(块级元素)
- transform: translate(x, y)(块级元素)
- flex(不定高,不定宽)(块级元素)
- grid(不定高,不定宽),兼容性相对比较差(块级元素)