以下面这段html
代码为例,container
为父元素,center
为子元素。其中根据父元素和子元素分别定宽高或者不定宽高的组合,分为四种情况来说明。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>水平垂直居中</title>
</head>
<body>
<div class="container">
<div class="center"></div>
</div>
</body>
</html>
一、父元素和子元素定宽高
1.绝对定位 + 偏移量50% + 负margin值
.container {
position: relative;
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background-color: pink;
}
2.绝对定位 + 偏移量50% + transform
.container {
position: relative;
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: pink;
}
3.绝对定位 + 偏移量0 + margin:auto
.container {
position: relative;
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: pink;
}
4.相对定位 + 偏移量50% + transform
.container {
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: pink;
}
5.相对定位+具体值
.container {
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
position: relative;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: pink;
}
6.flex布局
.container {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
width: 100px;
height: 100px;
background-color: pink;
}
7.line-height + text-align + vertical-align
.container {
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
background-color: aquamarine;
}
.center {
display: inline-block;
vertical-align: middle;
width: 100px;
height: 100px;
background-color: pink;
}
8.使用table-cell
.container {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
display: inline-block;
width: 100px;
height: 100px;
background-color: pink;
}
9.使用-webkit-box
.container {
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
width: 200px;
height: 200px;
background-color: aquamarine;
}
.center {
width: 100px;
height: 100px;
background-color: pink;
}
二、父元素定宽高,子元素不定宽高
用情况一中的2,3,4,6,7,8,9方法可以实现。
三、父元素不定宽高,子元素定宽高
用情况一中的1,2,3,4,6,7,8,9方法可以实现。
其中1,2,3方法需要把父容器的高度撑起来才能看到效果,可以用before
或after
或多添加一个div
给其设置高度,撑开父元素的高度,其他都大同小异。
四、父元素和子元素都不定宽高
这种情况下垂直居中其实没有多大意义,一般给父元素设置padding
值或者给子元素设置margin
值就能实现。