css垂直居中的方法
1.绝对定位+margin负值
html结构:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box{position:absolute;width:100px;height:200px;left:50%;top:50%;margin-top:-100px;margin-left:-50px;
background-color:#f00;}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
2.绝对定位+transform负值
html结构
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box {
position: absolute;
width: 100px;
height: 200px;
left: 50%;
top: 50%;
transform: translate(-50px, -100px);
background-color: #f00;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
3.绝对定位+margin:auto
注意(居中元素的父级元素必须有固定的宽和高)
html结构
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.div {
width: 500px;
height: 300px;
background-color: blue;
position: relative;
}
.box {
position: absolute;
width: 100px;
height: 200px;
left: 0;
top:0;
bottom: 0;
right: 0;
margin: auto;
background-color:#FFCFCF;
}
</style>
</head>
<body>
<div class="div">
<div class="box">
</div>
</div>
</body>
</html>
4.