块级元素水平和垂直方向居中的方法一共三种
1.先设置块级元素的宽高,然后利用定位和外边距将元素在水平和垂直方向上居中
示例:
<style>
.father{
width: 100%;
height: 500px;
position: relative;
}
.son{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
background-color: red;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
2.已知元素宽高,然后将父级元素设置为弹性盒,然后设置子级元素的外边距为自动
示例:
<style>
.father{
width: 100%;
height: 500px;
display: flex;
}
.son{
width: 100px;
height: 100px;
margin: auto;
background-color: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
</body>
3.已知元素宽高,然后利用定位和偏移量来设置元素水平和垂直方向上居中
示例:
<style>
.father{
width: 100%;
height: 500px;
position: relative;
}
.son{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
</body>
原文地址:https://www.cnblogs.com/hg845740143/p/12080214.html