垂直居中
需求:父子容器高度不固定情况下,实现子元素在父元素内居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试专用</title>
<style type="text/css">
.parent{background-color: gray; width: 100px; height: 300px;}
.child{background-color:orange;width: 100%; }
</style>
</head>
<body>
<div class="parent">
<div class="child">子容器</div>
</div>
</body>
</html>
解决方案1:table-cell + vertical-align
原理:将父元素设置为标单元格之后,vertical就可以生效了
.parent{display: table-cell;vertical-align: middle;}
- 优点:兼容性好,兼容到ie8+,对于更低版本,将结构换为table结构
- 缺点:会影响子元素内的元素,需要额外设置
解决方案2:absolute + transform
.parent{position: relative;}
.child{position: absolute;top: 50%;transform: translateY(-50%);}
- 优点:不影响其他元素
- 缺点:兼容问题
解决方案3:flex + align-items
原理:当设置父元素为flex,子元素变为flex-item,默认align-items是拉伸的,高度变为和父元素相同
.parent{display:flex;align-items:center;}
- 优点:只对父元素进行设置
- 缺点:兼容性问题
3616

被折叠的 条评论
为什么被折叠?



