1.負margin法:這是比較經常使用的方法,在知道元素的寬高的前提下才能使用web
1 <div id="a"></div> 2 3 #a{ 4 height:300px; 5 width:300px; 6 position:absolute; 7 top:50%; 8 left:50%; 9 margin-left:-150px; 10 margin-top:-150px; 11 }
注:負margin是個很是有意思的用法,深刻了解後會發現他在佈局上至關有用。
優勢:代碼量少,兼容性好。
缺點:非響應式方法,內容可能會超出容器。佈局
2.transform法:flex
<div id="a"></div> #a{ width: 50%; height: 20%; background: green; position: absolute; top:50%; left: 50%; transform:translate(-50%, -50%); -webkit-transform:translate(-50%, -50%); -ms-transform:translate(-50%, -50%); }
優勢:代碼量少;寬高可變,相應式佈局
缺點:不支持IE8,可能須要帶供應商前綴spa
3.Flexbox法code
<div class="vertical-container"> <div class="a"></div> </div> .vertical-container { height: 300px; width: 300px; background: #ccc; display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; } .a{ width: 200px; height: 200px; background: green; }
注:Flexbox的用法遠不止如此,在佈局上還有不少有趣的用法。orm
4.「徹底水平垂直居中」:必需要設置元素的高度,圖片自身有高度的能夠不設。blog
<div id="a"></div> #a{ width: 200px; height: 200px; background: red; margin:auto; position: absolute; top:0;left:0;right: 0;bottom: 0; }
優勢:代碼量少,兼容性好圖片
更多博客,前關注個人我的小站:http://eidolons-ailidan.rhcloud.com/博客