Web前端几种常见的实现水平垂直居中的方法

第一种:

       父容器不设置宽度,用定位实现水平垂直居中。

       

<!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>

猜你喜欢

转载自www.cnblogs.com/5274h/p/10747270.html