块级元素的垂直居中
一、已知块级元素的宽高,可以通过绝对定位+具体外边距来调整、
思路:子元素宽高已知,绝对定位top:50%,left:50%,此时,效果如图
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。设定的top:50%,left:50%,是针对于子元素的左上角,所以再利用外边距调整,将子元素的margin-top:调整为其-高度的一半,即(-height/2),margin-left同理,则实现了垂直居中
----------------代码-----------------
html:
<div class="top"> <div class="second"></div> </div>css:
.top { width: 200px; height: 300px; ">#16a085; position: relative; } .second { width: 100px; height: 50px; background-color: ">#bdc3c7; position: absolute; top: 50%; left: 50%; } 二、利用flex布局 思路:将父元素的display:flex,子元素margin:auto ----------------代码----------------- html: <div class="top"> <div class="second"></div> </div> css: /*只列出关键代码*/ top{ display:flex; } .second{ margin:auto; } 此种方式简单便捷,适用场景广泛,但使用时要注意浏览器是否支持flex布局 三、使用绝对定位+css3中的transform的translate 思路:其实与第一种绝对定位+外边距的方式思路相同,但不需要知道元素的具体宽度和高度,同时使用时要注意浏览器的兼容性 ----------------代码----------------- html: <div class="top"> <div class="second"></div> </div> css: .top { width: 200px; height: 300px; ">#16a085; position: relative; } .second { width: 100px; height: 50px; ">#bdc3c7; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%) } 四、已知元素宽高,使用绝对定位设置其距离父元素的top,right,left,bottom都为0,再设置margin:auto,即可实现垂直居中
更多精彩