垂直居中
- 行内元素,可以设置line-height 与父级 height 相等
- 设置 margin/padding 居中
- flex 居中 设置 align-items:center
- 绝对定位居中
案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>垂直居中案例</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box{
width: 200px;
height: 200px;
border: 1px solid #a124aa;
margin: 0 auto;
}
.box>.main{
width: 50px;
height: 50px;
background-color: aquamarine;
}
/* 上方是公共样式 */
/* 让main在大盒子里居中 */
/* 一 */
.box1>p{
line-height: 200px;
}
/* 方式二 */
.box2{
padding-top: 75px;
}
/* 方式三 */
.box3{
display: flex;
justify-content: space-between;
align-items: center;
}
/* 方式四 */
.box4{
position: relative;
}
.box4>.main{
position: absolute;
top: 0; /* 用于垂直居中 */
bottom: 0; /* 用于垂直居中 */
right: 0;
left: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box box1">
<!-- 垂直居中 内联元素span 和 块元素 p -->
<p>123</p>
</div>
<div class="box box2">
<!-- 垂直居中 方式二 -->
<p class="main"></p>
</div>
<div class="box box3">
<!-- 垂直居中 方式三 -->
<p class="main"></p>
<span>1234</span>
</div>
<div class="box box4">
<!-- 垂直居中 方式四 -->
<p class="main"></p>
</div>
</body>
</html>