参考:
CSS常见布局及解决方案
把简单做好也不简单-css水平垂直居中
单行文本垂直居中
需要满足两个条件:
1.元素内容是单行,并且其高度是固定不变的。
2.将其line-height设置成和height的值一样
<div><span>这是一段文字</span></div>
div{
width: 400px;
height: 300px;
border: 1px solid #000;
}
span{
line-height: 300px;
}
1.父节点:table-cell + vertical-align
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
display: table-cell;
vertical-align: middle;
}
.child {
background-color: #fe6464;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
兼容性好(IE 8以下版本需要调整页面结构至 table)
效果图
2.定位法1:父节点:relative + 子节点:absolute + transform
强大的absolute对于这种小问题当然也是很简单的。
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
position: relative;
}
.child {
background-color: #fe6464;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
绝对定位脱离文档流,不会对后续元素的布局造成影响。
但如果绝对定位元素是唯一的元素则父元素也会失去高度。
子节点:
position: absolute;
top: 50%;
// 注意此时子节点不设置height为100px
-webkit-transform: translate(0,-50%);
-ms-transform: translate(0,-50%);
-o-transform: translate(0,-50%);
transform: translate(0,-50%);
transform 为 CSS3 属性,有兼容性问题
同水平居中,这也可以用margin-top实现,原理水平居中
效果图:
3.定位法2:父节点:relative + 子节点absolute + margin-top
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
position: relative;
}
.child {
background-color: #fe6464;
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
需要指定高度
运用css3中的clac()属性能简化部分代码:
position: absolute;
height: 100px;
/* 核心 */
top: calc(50% - 50px);
效果图:
4.父节点:flex + align-items
如果说absolute强大,那flex只是笑笑,因为,他才是最强的。。。但它有兼容问题
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
display: flex;
align-items: center;
}
.child {
background-color: #fe6464;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
效果图: