不定宽度的盒子模型水平垂直居中
1、兼容最佳
<body>
<div id="box">
<div class="content"></div>
</div>
</body>
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以下都会出现问题。
2、实现最佳
<body>
<div id="box">
<div class="content"></div>
</div>
</body>
body,html { margin:0; width:100%; height:100%; }
#box { width:100%; height:100%; text-align:center; position:relative; background:rgba(0,0,0,0.7); }
#content{ position:absolute; width:50%; height:50%; background:pink; left:50%; top:50%; transform:translateX(-50%) translateY(-50%);
-webkit-transform:translateX(-50%) translateY(-50%); }
第二种利用transform进行元素偏移。这方法功能很强大,也比较灵活,不仅仅局限在实现居中显示。 兼容方面也一样拿IE来做比较,第二种方法IE8以上都能使用。 IE8及IE8以下都会出现问题。
3、最简单
<body>
<div id="box">
<div class="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:flex; display:-webkit-flex; justify-content:center; align-items:center; }
#content {position:absolute; width:50%; height:50%; background:pink; }
第三种利用弹性盒模型进行布局,很简单几句代码就实现了。但是IE浏览器并不支持display:flex;

浙公网安备 33010602011771号