码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-07-17 16:17:21      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:com   abs   技术   ati   pyc   移动   idt   今天   垂直居中   

今天做 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自适应浏览器窗口居中显示

标签:com   abs   技术   ati   pyc   移动   idt   今天   垂直居中   

原文地址:http://www.cnblogs.com/libin6505/p/7195899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
分享档案
周排行
mamicode.com排行更多图片
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!