css 垂直居中的几种手段
- height + line-height
- vertical-align
- padding
- flex + align-items
- 绝对定位 + margin: auto
- 绝对定位 + margin:-height/2
- 绝对定位 + transform
- flex + flex-direction
- grid
height + line-height
使用:父元素 为 block 元素,子元素为 display: inline-block 元素。
.parent{
display: block;
height: 120px;
line-height: 120px;
text-align:center;
}
.son {
display: inline-block;
}
复制代码
vertical-align: middle
使用: 利用 vertical-align: middle 实现
.parent {
display: table;
width: 120px;
height: 120px;
text-align:center;
}
.son {
display:table-cell;
vertical-align: middle;
}
复制代码
padding
使用:当确定子 元素 宽度和高度的时候使用
.parent {
display: block;
width:120px;
padding: 80px 0;
text-align:center;
}
.son {
height: 80px;
line-height: 80px;
width: 120px;
}
复制代码
flex+align-items
使用: 兼容性
.parent {
display:flex;
width: 120px;
height: 120px;
text-algin:center;
align-items:center;
}
.son {
width:60px;
}
复制代码
绝对定位 + margin: auto
使用:当确定子 元素 宽度和高度的时候使用
.parent {
display: block;
width:120px;
height:120px;
position:relative;
text-align:center;
}
.son {
position:absolute;
margin: auto;
top: 0;
bottom: 0;
width: 120px;
height: 50px;
line-height: 50px;
}
复制代码
绝对定位 + margin:-height/2
使用:当确定子 元素 宽度和高度的时候使用
.parent {
display: block;
width:120px;
height:120px;
position:relative;
text-align:center;
}
.son {
position:absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
line-height: 50px;
margin-left: -25px;
margin-top: -25px;
}
复制代码
绝对定位 + transform
使用:兼容性
.parent {
position:relative;
width: 120px;
height: 120px;
text-align:center;
}
.son {
position:absolute;
top: 50%;
width: 100%;
transform: translateY(-50%);
}
复制代码
flex+flex-direction
使用:兼容性
.parent {
display:flex;
width:120px;
height: 120px;
flex-direction: column;
justify-content: center;
}
.son {
height: 80px;
width: 180px;
line-height: 80px;
}
复制代码
Grid
使用: 兼容性
.parent {
width: 200px;
height: 200px;
display: grid;
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END