29.水平居中,垂直居中的几种方式

xiaoxiao2021-02-28  32

垂直水平居中的方案有很多,有时候容易搞混。其实细分下来主要有两种场景:元素宽高未知的场景、元素宽高已知的场景。针对这两种情况,后文分别列出集中主流的垂直水平居中方案。

元素宽高未知的场景

table 实现垂直水平居中【推荐】

table垂直水平居中方案,是万金油方案,适用性极强,也没有兼容性问题;缺陷是会增加冗余的HTML结构。

<div class="vertical center"> <div class="box-container"> <span class="box">haha</span> </div> </div> .vertical { width: 100%; height: 100%; display: table; } .vertical.center { text-align: center; } .vertical .box-container { display: table-cell; vertical-align: middle; 把元素放在父元素的中部 } .vertical .box-container .box { vertical-align: middle; }

transform 实现垂直水平居中【推荐】

transform垂直水平居中方案,同样也是万金油方案,尤其适合移动端;缺陷是只支持IE9及以上的浏览器。

<span class="box">haha</span> // transform是以自身宽高为基准计算的 .box { position: relative; left: 50%; top: 50%; transform: translate(-50%, -50%); }

兼容性:ie9以下不支持 transform,手机端表现的比较好。

flexbox 实现垂直水平居中

<div class="box-container"> <span class="box"></span> </div> // transform是以自身宽高为基准计算的 .box-container { display: -webkit-flex; display: -moz-flex; display: -ms-flex; display: -o-flex; display: flex; justify-content: center; align-items: center; }

移动端首选

移动端可以使用;缺陷是只支持IE10及以上的浏览器。

元素宽高已知的场景

绝对定位 实现垂直水平居中

比较常用的方案,需要已知宽高。

<div class="box-container"> <span class="box"></span> </div> .box-container{ position: relative; } .box-container .box { width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; margin-top: -200px; /* 高度的一半 */ margin-left: -300px; /* 宽度的一半 */ }

兼容性:适用于所有浏览器

margin:auto 实现垂直水平居中

特别适合自身有宽高的元素,比如图片等;但是对于其他元素,仍然需要显式设置宽高。

// 图片等自身带宽高的元素,直接 margin: auto; 即可 <div class="box-container"> <img class="box" /> </div> .box-container{ position: relative; } .img { position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } // 其他场景需要显式设置宽高 <div class="box-container"> <span class="box"></span> </div> .box-container{ position: relative; } .box { width: 100px; height: 100px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; }

兼容性:主流浏览器均支持,IE6不支持

另外一种:兼容低版本浏览器,不固定宽高

<!-- html --> <div class="table"> <div class="tableCell"> <div class="content">不固定宽高,自适应</div> </div> </div> /*css*/ .table { height: 200px;/*高度值不能少*/ width: 200px;/*宽度值不能少*/ display: table; position: relative; float:left; background: yellow; } .tableCell { display: table-cell; vertical-align: middle; text-align: center; *position: absolute; padding: 10px; *top: 50%; *left: 50%; } .content { *position:relative; *top: -50%; *left: -50%; background: green; } 重点参考:1.https://www.jianshu.com/p/def2bd11cdb7   优缺点:固定宽高,PC 手机端,兼容性                 2.https://www.jianshu.com/p/8a35f7ab6bc9                 3.https://www.jianshu.com/p/09ece194956a 垂直 水平分开讲 比较细 作者:Mr丶ing 链接:https://www.jianshu.com/p/def2bd11cdb7 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者:齐修_qixiuss 链接:https://www.jianshu.com/p/8a35f7ab6bc9 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

转载请注明原文地址: https://www.6miu.com/read-2649983.html

最新回复(0)