页面排版的时候,会遇到一个需要将div或者其他元素垂直居中到容器的问题,实现的示例效果如图所示:

实现
- 先说下传统做法,在知道父容器高度的情况下,使用position: relative; top: 50%; transform: translateY(-50%);
<!doctype html>
<html>
<head>
<style>
.parent {
background: blue;
width: 400px;
height: 400px;
}
.child {
width: 100px;
height: 100px;
background: green;
/* 水平居中 */
margin: 0 auto;
/* 以下三行实现垂直居中 */
position: relative;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
</div>
</div>
</body>
</html>
- 不知道高度的情况下,或者更加现代一些的做法,就是利用flex布局,设置justify-content和align-items为center,来看下例子:
<!doctype html>
<html>
<head>
<style>
html,
body {
height: 100%;
}
.parent {
background: blue;
width: 400px;
height: 100%;
display: flex;
justify-content: center;
/* align horizontal */
align-items: center;
/* align vertical */
}
.child {
width: 100px;
height: 100px;
background: green;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
</div>
</div>
</body>
</html>
文章评论