<div id="parent">
<!-- 定义子级元素 -->
<div id="child">居中布局</div>
</div>
通过以下CSS样式代码实现水平方向居中布局效果
.parent{position:relative;}
.child{position: absolute;top: 50%;transform: translateY(-50%)}
优点:
父级元素是否脱离文档流, 不影响子级元素垂直居中效果
缺点:
transform属性是CSS3中新增属性, 浏览器支持情况不好
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>垂直居中布局的第二种解决方案</title>
<style>
#parent {
width: 200px;
height: 600px;
background: #ccc;
position: relative;
}
#child {
width: 200px;
height: 200px;
background: #c9394a;
position: absolute;
top: 50%;
transform: translateY(-50%)
}
</style>
</head>
<body>
<!-- 定义父级元素 -->
<div id="parent">
<!-- 定义子级元素 -->
<div id="child"></div>
</div>
</body>
</html>