第一種:
父容器不設置寬度,用定位實現水平垂直居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>實現垂直居中</title>
<style>
.father{
height: 1000px;
background-color: hotpink;
position: relative;
}
.son{
width: 200px;
height: 200px;
position: absolute;
left:50%;
top:50%;
margin:-100px 0px 0px -100px;
background: red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
第一種:
用flex實實現水平垂直居中。這個是最常見的方法,經常會用到的。
父容器
.father{
height: 500px;
background-color: hotpink;
display:flex;
}
子容器
.son{
margin:auto;
background-color: skyblue;
width: 100px;
height: 100px;
}
這樣就實現了水平垂直居中啦
最后一種也是常用的水平垂直居中方法:直接上代碼
.containter{
height: 1200px;
background-color: lavender;
display: flex;
flex-wrap: wrap;
}
.item1,.item2,.item3,.item4 {
width: 450px;
height: 500px;
vertical-align: middle;
display: table-cell;
margin:auto;
text-align: center;
}
.item1 img,.item2 img,.item3 img,.item4 img {
display:inline-block;
width: 450px;
height: 500px;
}
<div class="containter">
<div class="item1"><img src="img/img-27f9268b8eec512d3a105dc2332845bd(1).jpg" alt=""></div>
<div class="item2"><img src="img/img-3cf02d3a912a0b2e4fe8f37bd1ad3476.jpg" alt=""></div>
<div class="item3"><img src="img/img-6fd020679750aaf7015245a84188c410.jpg" alt=""></div>
<div class="item4"><img src="img/img-b69563d9e8a36206cb8f8fe5c9e2d25f.jpg" alt=""></div>
</div>