CSS实现垂直居中的方法
生活随笔
收集整理的這篇文章主要介紹了
CSS实现垂直居中的方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
CSS實(shí)現(xiàn)垂直居中的方法
1、relative absolute定位:
(1)css html代碼
1 <!doctype html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8" /> 6 <title>Document</title> 7 <style type="text/css"> 8 * { 9 margin: 0; 10 padding: 0; 11 } 12 13 .parent { 14 width: 400px; 15 height: 400px; 16 margin: 100px; 17 border: 1px solid red; 18 position: relative; 19 } 20 21 .child { 22 width: 200px; 23 height: 200px; 24 border: 1px solid green; 25 position: absolute; 26 top: 0; 27 left: 0; 28 right: 0; 29 bottom: 0; 30 margin: auto; 31 } 32 </style> 33 </head> 34 35 <body> 36 <div class="parent"> 37 父元素 38 <div class="child"> 39 子元素 40 </div> 41 </div> 42 </body> 43 44 </html>(2)效果
(3)兼容性
兼容全部瀏覽器
2、flex布局:
(1)html css代碼
1 <!doctype html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8" /> 6 <title>Document</title> 7 <style type="text/css"> 8 * { 9 margin: 0; 10 padding: 0; 11 } 12 13 .parent { 14 width: 400px; 15 height: 400px; 16 margin: 100px; 17 border: 1px solid red; 18 display: flex; 19 justify-content: center; 20 align-items: center; 21 } 22 23 .child { 24 width: 200px; 25 height: 200px; 26 border: 1px solid green; 27 } 28 </style> 29 </head> 30 31 <body> 32 <div class="parent"> 33 <div class="child"> 34 子元素 35 </div> 36 </div> 37 </body> 38 39 </html>?
?
(2)效果
(3)兼容性
根據(jù)caniuse(http://caniuse.com/#search=flex)
對(duì)于IE瀏覽器,需要IE10以及以上。
3、relative transform定位:
(1)html css代碼
1 <!doctype html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8" /> 6 <title>Document</title> 7 <style type="text/css"> 8 * { 9 margin: 0; 10 padding: 0; 11 } 12 13 .parent { 14 width: 400px; 15 height: 400px; 16 margin: 100px; 17 border: 1px solid red; 18 } 19 20 .child { 21 width: 200px; 22 height: 200px; 23 border: 1px solid green; 24 position: relative; 25 top: 50%; 26 left: 50%; 27 transform: translate(-50%, -50%); 28 } 29 </style> 30 </head> 31 32 <body> 33 <div class="parent"> 34 <div class="child"> 35 子元素 36 </div> 37 </div> 38 </body> 39 40 </html>?
(2)效果
(3)兼容性
根據(jù)caniuse(http://caniuse.com/#search=translate)
對(duì)于IE瀏覽器,需要IE10以及以上。
?
總結(jié):
根據(jù)項(xiàng)目瀏覽器兼容性要求,選擇合適的垂直居中的方案。方案2和方案3適合用在移動(dòng)端項(xiàng)目,方案1兼容性方面最好。
更多專業(yè)前端知識(shí),請上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的CSS实现垂直居中的方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 移动端网页宽度值(未加meta view
- 下一篇: CSS媒体查询