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.

posted @ 2019-07-27 19:46  星雨,恒奋斗,过客  阅读(150)  评论(0编辑  收藏  举报