在日常开发中,经常会遇到要求水平垂直居中效果
实现水平垂直居中也是面试高频考点
水平垂直居中又分两种情况
1.内容定宽高
2.内容不定宽高
内容定宽高
1.绝对定位和负margin值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>水平垂直居中效果</title>
<style>
.box{
width: 200px;
height: 200px;
border: 1px solid #000;
position: relative;
}
.content{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
</head>
<body>
<div class="box">
<div class="content">
</div>
</div>
</body>
</html>
效果
2.绝对定位+left/right/top/bottom + margin
方法简单好记
<div class="box">
<div class="content">
</div>
</div>
<style>
.box{
width: 200px;
height: 200px;
border: 1px solid #000;
position: relative;
}
.content{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
内容不定宽高
不定宽高的方法也可以用于定宽高的情况
1.绝对定位+transfrom
主要用css3中的变形 向上向左平移自身的一半
<div class="box">
<span class="content">我是中间内容</span>
</div>
<style>
.box{
width: 200px;
height: 200px;
border: 1px solid #000;
position: relative;
}
.content{
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
效果:
2.flex布局
<div class="box">
<span class="content">我是中间内容</span>
</div>
<style>
.box{
width: 200px;
height: 200px;
border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
}
.content{
background-color: pink;
}
</style>
3.grid布局
<div class="box">
<span class="content">我是中间内容</span>
</div>
<style>
.box{
width: 200px;
height: 200px;
border: 1px solid #000;
display: grid;
}
.content{
background-color: pink;
align-self: center;
justify-self: center;
}
</style>
4.display:table-cell
类似将容器变成表格中的单元格
<div class="box">
<span class="content">我是中间内容</span>
</div>
<style>
.box{
width: 200px;
height: 200px;
border: 1px solid #000;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.content{
background-color: pink;
}
</style>
另外文字垂直居中用text-align:center 和 line-height 值为容器高度
图片垂直居中可以用容器的伪元素作为图片的参照物来垂直居中
.box:after{
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
text-align: center;
}
img{
vertical-align: middle;
}