块级元素垂直居中(position方法),
css部分:
*{padding: 0;margin: 0;}
body,html,.wrap{width: 100%;height: 100%;}
.wrap{background: red;position: relative;}
.box{position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);-webkit-transform: translate(-50%,-50%);width: 100px;height: 100px;background: yellow;}
html部分:
<div class="wrap">
<div class="box"></div>
</div>
效果图:
心得:
父元素宽高不定,设为body,html,.wrap{width: 100%;height: 100%;}
子元素设置样式.box{;width: 100px;height: 100px;background: yellow;},添加绝对定位position: absolute;,
子元素绝对定位后,父元素添加相对定位.wrap{background: red;position: relative;}
子元素垂直居中top: 50%;left: 50%;transform: translate(-50%,-50%);-webkit-transform: translate(-50%,-50%);
哇咔咔~希望对小伙伴们有帮助呀~~