一、在一个div里的div左右垂直居中
条件1:已知box1,box2宽高
条件2:已知box1宽高,box2宽高未知(即box2宽高是可变的)
<div class="box1">
<div class="box2"></div>
</div>
通用method1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{width: 500px;height: 500px;border: 1px solid red;text-align: center;}
.box2{width: 200px;height: 200px;border:1px solid green;display:inline-block;vertical-align: middle;}
span{width: 0;height: 100%;display: inline-block;vertical-align: middle;}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
<span></span>
</div>
</body>
</html>
通用method2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{width: 500px;height: 500px;border: 1px solid red;display: table-cell;vertical-align: middle;}
.box2{width: 200px;height: 200px;border:1px solid green;margin: 0 auto;}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
通用method3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{width: 500px;height: 500px;border: 1px solid red;position: relative;}
.box2{width: 200px;height: 200px;border:1px solid green;position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
通用method4:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{width: 500px;height: 500px;border: 1px solid red;position: relative;}
.box2{width: 200px;height: 200px;border:1px solid green;position: absolute;
top: 50%;left: 50%;transform:translate(-50%,-50%);}//使用css3属性
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
box2宽高已知时:(或不用定位,计算后用margin来实现)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{width: 500px;height: 500px;border: 1px solid red;position: relative;}
.box2{width: 200px;height: 200px;border:1px solid green;position: absolute;top: 50%;left: 50%;margin: -100px 0 0 -100px;}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
当需要文字(inline)居中时:line-height:容器高度; text-align:center;(父元素)
当需要图片居中时:可用method1或给父元素line-height:容器高度;img vertical-align:middle;