一,固定高度垂直居中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css垂直居中</title>
<style type="text/css">
.contaniner{
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -150px;
width: 300px;
height: 300px;
border: 1px solid #000;
}
/*简化写法*/
/*.contaniner {
position: absolute;
left: calc(50% - 150px);
top: calc(50% - 150px);
width: 300px;
height: 300px;
border: 1px solid #000;
}*/
</style>
</head>
<body>
<div class="contaniner">
Hello Word!
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css垂直居中</title>
<style type="text/css">
.contaniner{
position: absolute;
top:0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 300px;
height: 300px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div class="contaniner">
Hello Word!
</div>
</body>
</html>
二,高度随内容撑开(自适应高度)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css垂直居中(2种)</title>
<style type="text/css">
.contaniner3 {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid #000;
}
/*.contaniner4{
width: 300px;
margin: 50vh auto;
border: 1px solid #000000;
transform: translateY(-50%);
}*/
</style>
</head>
<body>
<!--利用transform的translate属性进行居中显示-->
<div class="contaniner3">
Hello Word!
</div>
<!--利用margin:50vh 通过 transform居中显示-->
<!--<div class="contaniner4">
Hello Word!
</div>-->
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css垂直居中(flex加vh)</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.contaniner5{
display: flex;
height: 100vh;
}
.inner{
margin: auto;
}
</style>
</head>
<body>
<div class="contaniner5">
<div class="inner">
Hellow Word!
</div>
</div>
</body>
</html>