方式一、利用绝对定位的方式+margin:auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS垂直居中</title>
<style>
.wrapper{
width: 500px;
height: 500px;
background-color: pink;
/*方式一*/
position: relative;
}
.box{
width: 100px;
height: 100px;
background-color: deepskyblue;
/*方式一*/
position: absolute;
left:0;
right: 0;
top:0;
bottom:0;
margin: auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>
方式二、利用绝对定位的方式+margin反向偏移
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS垂直居中</title>
<style>
.wrapper {
width: 500px;
height: 500px;
background-color: pink;
/*方式二*/
position: relative;
}
.box {
width: 100px;
height: 100px;
background-color: deepskyblue;
/*方式二*/
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px; /*1/2的width*/
margin-top: -50px; /*1/2的height*/
/*transform:translate(-50%,-50%);代替上两行,这样即使宽高不固定也能实现水平垂直居中*/
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>
方式三、基于属性的计算
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS垂直居中</title>
<style>
.wrapper {
width: 500px;
height: 500px;
background-color: pink;
/*方式三*/
overflow: hidden;
}
.box {
width: 100px;
height: 100px;
background-color: deepskyblue;
/*方式三*/
margin: calc(50% - 50px) auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>
calc()从字面我们可以把他理解为一个函数function。其实calc是英文单词calculate(计算)的缩写,是css3的一个新增的功能,用来指定元素的长度。
方式四、基于vertical-align属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS垂直居中</title>
<style>
.wrapper{
width: 500px;
height: 500px;
background-color: pink;
/*方式四*/
text-align: center;
}
.box{
width: 100px;
height: 100px;
background-color: deepskyblue;
/*方式四*/
display: inline-block;
vertical-align: middle;
}
/*方式四的辅助元素*/
.help{
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
<!--方式四-->
<div class="help"></div>
</div>
</body>
</html>
方式五、使用弹性盒子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS垂直居中</title>
<style>
.wrapper{
width: 500px;
height: 500px;
background-color: pink;
/*方式五*/
display: flex;
justify-content: center;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background-color: deepskyblue;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>
方式六、基于块级内联元素的特性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS垂直居中</title>
<style>
.wrapper {
width: 500px;
height: 500px;
background-color: pink;
/*方式六*/
line-height: 550px; /*.wrapper.height+1/2*box.height*/
text-align: center;
}
.box {
width: 100px;
height: 100px;
background-color: deepskyblue;
/*方式六*/
display: inline-block;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>