libin6505

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

 

分类:

技术点:

相关文章:

  • 2021-12-01
  • 2021-11-21
  • 2021-11-17
  • 2022-02-09
  • 2021-11-21
  • 2021-12-09
  • 2021-12-10
  • 2021-12-20
猜你喜欢
  • 2021-12-02
  • 2021-12-15
  • 2021-09-07
  • 2021-12-27
  • 2021-09-07
  • 2021-05-16
相关资源
相似解决方案