让div自适应浏览器窗口居中显示

让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向左向上移动它自身宽高的一半,最终效果:

 

posted @ 2017-07-17 16:06  戈博折刀  阅读(353)  评论(0编辑  收藏  举报