【css】不定宽高的div水平、垂直居中问题

一、兼容最佳html

    <body>
        <div id="box">
            <div id="content"></div>
        </div>        
    </body>web

    body,html { margin:0; width:100%; height:100%; }
     
    #box { width:100%; height:100%; background:rgba(0,0,0,0.7); position:relative;}
    #content { width:50%; height:50%; background:pink; position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; }浏览器

第一种方法也是出现的比较早的了。兼容拿IE来作参照——>第一种方法IE7以上都能使用,IE7及IE7如下都会出现问题。
 布局


二、实现最佳flex

    <body>
        <div id="box">
            <div id="content"></div>
        </div>        
    </body>flexbox

    body,html { margin:0; width:100%; height:100%; }
     
    #box { width:100%; height:100%; background:rgba(0,0,0,0.7); position:relative; }
    #content{ position:absolute; width:50%; height:50%; background:pink; left:50%; top:50%;  
    transform:translateX(-50%) translateY(-50%);
    -webkit-transform:translateX(-50%) translateY(-50%); }.net

第二种利用transform进行元素偏移。这方法功能很强大,也比较灵活,不单单局限在实现居中显示。  兼容方面也同样拿IE来作比较,第二种方法IE8以上都能使用。  IE8及IE8如下都会出现问题。
 orm

三、代码最简单①htm

    <body>
        <div id="box">
            <div id="content"></div>
        </div>        
    </body>blog

    body,html { margin:0; width:100%; height:100%; }
     
    #box { width:100%; height:100%; background:rgba(0,0,0,0.7); display:flex; display:-webkit-flex; justify-content:center; align-items:center; }
    #content {position:absolute; width:50%; height:50%; background:pink; }

第三种利用弹性盒模型进行布局,很简单几句代码就实现了。惋惜IE浏览器并不怎么支持display:flex;

 

 
四、代码最简单②

    <body>
        <div id="box">
            <div id="content"></div>
        </div>        
    </body>

    body,html { margin:0; width:100%; height:100%; }  
      
    #box { width:100%; height:100%; background:rgba(0,0,0,0.7); display:box; box-pack:center;
    box-align:center; display:-webkit-flexbox; -webkit-box-pack:center; -webkit-box-align:center; }  
    #content { width:50%; height:50%; background:pink; }  

第三种用的也是弹性盒模型进行布局,不过相对于display:flex;来讲,display:box;是较老版本的弹性盒模型。也是很简单几句代码就实现了。惋惜IE浏览器也并不支持display:box;

抄袭:https://blog.csdn.net/w390058785/article/details/77992457