讓div自適應瀏覽器窗口居中顯示
阿新 • • 發佈:2017-07-17
col style comm 適應 http img relative 水平 mar
讓div自適應瀏覽器窗口居中顯示
轉載自:http://www.cnblogs.com/qiye2016/p/5492983.html今天做 banner 時發現一個問題,就是瀏覽器窗口水平拉伸時 banner 圖未能居中,所以網上找了些資料,自己寫了個小 demo
html代碼:
<div class="div1"> <div class="div2">自適應瀏覽器水平垂直居中</div> </div>
css代碼:
.div1{ width: auto; height: 600px; background: #cccccc; position: relative; } .div2{ position: absolute; left: 50%; top: 50%; margin-left: -600px; margin-top: -200px; width: 1200px; height: 400px; background: #4fcc8d; line-height: 400px; font-size: 36px; text-align: center; }
原理就是,先用 left:50%; top:50%; 讓這個 div 的左上角位於頁面正中,如圖:
然後再利用 margin-left:-600px;margin-top:-200px;使div向左向上移動它自身寬高的一半,最終效果:
讓div自適應瀏覽器窗口居中顯示