css垂直居中的几种方法
- 这个是先把父级元素的position设置为relative;然后子元素设置为position:absolute;
然后设置子元素:top:50%; transform:translateY(-50%),记住,这样做的前提是父元素和子元素都有实际的高度。
这样也可以:top:50%; margin-top:-50px;
两种方法的原理其实是一样的,都是先把子元素下移50%父元素的高度,然后再上移自身高度的50%;注意,用margin-top时,要用实际高度,不能用百分数表示。
-
1 <style> 2 - .parent { 3 - width:200px; 4 - height:200px; 5 - background-color:#ccc; 6 - position:relative; 7 - } 8 - .child { 9 - width:100px; 10 - height:100px; 11 - background:#e4393c; 12 - position:absolute; 13 - top:50%; 14 - transform:translateY(-50%); 15 //margin-top:(-50px)(这样也可以) 16 - } 17 - </style> 18 - </head> 19 20 <body> 21 <div class="parent"> 22 <div class = "child"></div> 23 </div> 25 </body>
2.这种方法用的是flex布局,先把父级display:flex;
然后设置align-items: center(这是设置父元素里的元素垂直居中),justify-content:center(设置父元素里的子元素水平居中);
代码如下:
<style> .parent { width:200px; height:200px; background-color:#ccc; display:flex; align-items:center; justify-content:center; } .child { width:100px; height:100px; background:#e4393c; position:absolute; } </style> </head> <body> <div class="parent"> <div class = "child"></div> </div> </body>
3.这个方法直接上代码,父元素设置position:relative;子元素设置positio:absolute,然后设置子元素top:0;bottom:0;margin-top:auto; 值得注意的是,
top和bottom值要设置相等就可以,不一定为0;
<style> #box { width: 300px; height: 300px; background: #ddd; position: relative; } #child { width: 200px; height: 100px; background: #A1CCFE; position: absolute; top: 0; bottom: 0; margin: auto; line-height: 100px; } </style> </head> <body> <div id="box"> <div id="child">呆呆今天退役了(。﹏。)</div> </div> </body>
4.还有一种方法也可以,其实也是flex 的一种,主要设置宽高,然后设置父元素:display:flex; flex-direction:column;justify-content:center;

浙公网安备 33010602011771号