700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 不设置DIV的宽高 让它相对于页面水平垂直居中

不设置DIV的宽高 让它相对于页面水平垂直居中

时间:2022-02-08 22:11:07

相关推荐

不设置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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。