一、行内元素的垂直居中方法
核心:line-height = height
例:
<div class="box">
<span class="span">content</span>
</div>
<style>
.box{
height: 100px;
border: 1px solid blueviolet;
}
.id{
line-height: 100px;
text-align: center;
}
</style>
二、块级元素absoulute定位元素
1、利用top+margin-top
<div class="fu">
<div class="zi"></div>
</div>
.fu{
width: 500px;
height: 500px;
position: relative;
}
.zi{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
left: 50%;
margin-left: -50px
}
2、利用transform
<div class="fu">
<div class="zi"></div>
</div>
.fu{
width: 500px;
height: 500px;
position: relative;
}
.zi{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
3、不存在兼容性问题的一种方式
<div class="fu">
<div class="zi"></div>
</div>
.fu{
width: 500px;
height: 500px;
position: relative;
}
.zi{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
这种方式时最适合的,当父盒子或者子盒子尺寸发生变化时,子元素会自适应垂直居中。