zoukankan      html  css  js  c++  java
  • 不设置DIV的宽高,让它相对于页面水平垂直居中

    一、第一种方法,通过transform实现实现

    body,html { margin:0; width:100%; height:100%; }
    #box { 
        width:100%; 
        height:100%; 
        background: gray;
        position:relative; 
    }
    #content{ 
        position:absolute; 
        width:30%; 
        height:30%; 
        background:pink; 
    }
    .center{
        left:50%; 
        top:50%;  
        transform: translate(-50%, -50%);
        /* transform:translateX(-50%) translateY(-50%);  */
    }
    <!-- 通过transform实现 -->
        <div id="box">
            <div id="content" class="center">transform只支持IE9以上,IE8及IE8以下都会出现问题。</div>
        </div> 

    第二种 、通过display:flex实现,只支持IE10及以上

    body,html { margin:0; width:100%; height:100%; }
    #box2 { 
        width:100%; 
        height:100%; 
        background: gray;
        display:flex; 
        justify-content:center; 
        align-items: center;
    }
    #content2 {
        width:30%;
        height:30%; 
        background:pink;
    }
    <!-- 通过display:flex实现,只支持IE10及以上 -->
        <div id="box2">
            <div id="content2">display:flex;只支持IE10及以上</div>
        </div> 

    第三种、通过定位,margin:auto实现,兼容最好

    body,html { margin:0; width:100%; height:100%; }
    #box3 { 
        width:100%; 
        height:100%; 
        background: gray;
        position:relative;
    }
    #content3 { 
        width:30%; 
        height:30%; 
        background:pink; 
        position:absolute; 
        top:0; 
        right:0;
        bottom:0;
        left:0; 
        margin:auto; 
    }
    <!-- 通过margin:auto实现,兼容最好 -->
        <div id="box3">
            <div id="content3">兼容最好,支持到IE8</div>
        </div>

  • 相关阅读:
    检测是否安装了新包
    redux和mobx的比较
    ssh登录远程服务器
    法律
    如何解决二方包彼此依赖?
    创业
    【转】裸辞4个月,面试30家公司。
    添加群机器人
    RESTful状态码说明
    MongoDB简单介绍以及基本命令
  • 原文地址:https://www.cnblogs.com/tanweiwei/p/10654159.html
Copyright © 2011-2022 走看看