css关于垂直居中的几种方法
不知道子元素的宽度和高度的情况下,
1.可以通过“子绝父相”的规则
.parent {
background-color: red;
width: 300px;
height: 500px;
position: relative;
}
.son {
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
- 利用flex布局的巧妙思想
.parent{
background-color: red;
width: 300px;
height: 500px;
display: flex;
justify-content: center;//容器元素水平对齐
align-items: center;//容器元素垂直对齐
}
- 利用
table-cell
display:table-cell
会使元素呈现表格中的单元格的属性,实现对文字的垂直居中。但是会破坏css的一些属性:
1.不能与float
与position:absolute
一起使用,
2.margin
设置无效,响应padding
设置,
3.对高度和宽度非常敏感,
4.不要对display:table-cell 使用百分比来设置宽度和高度
.parent{
display: table-cell;
width: 300px;
height: 500px;
background-color:red;
vertical-align: middle;
text-align: center;
}
还有一种是在知道子元素的宽度和高度下才可以
.parent {
background-color: red;
width: 300px;
height: 500px;
position: relative;
}
.son {
width: 80px;
height: 30px;
background-color: green;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}