css如何实现水平垂直居中

方法居中元素定宽高固定PC兼容性移动端兼容性
absolute + 负margin ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
absolute + margin auto ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
absolute + calc ie9+, chrome19+, firefox4+ 安卓4.4+, iOS6+
absolute + transform ie9+, chrome4+, firefox3.5+ 安卓3+, iOS6+
writing-mode ie6+, chrome4+, firefox3.5+ 安卓2.3+, iOS5.1+
lineheight ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
table ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
css-table ie8+, chrome4+, firefox2+ 安卓2.3+, iOS6+
flex ie10+, chrome4+, firefox2+ 安卓2.3+, iOS6+
grid ie10+, chrome57+, firefox52+ 安卓6+, iOS10.3+

后面不在重复这段公共代码:

【HTML 代码】:

1 <div class="wp">
2     <div class="box">123123</div>
3 </div>

【CSS 代码】;

 1 /* 公共代码 */
 2 .wp {
 3     border: 1px solid red;
 4     width: 300px;
 5     height: 300px;
 6 }
 7 
 8 .box {
 9     background: green;    
10 }
11 
12 .box.size{
13     width: 100px;
14     height: 100px;
15 }
16 /* 公共代码 */

+++++++++ 固定高度宽度 添加类size++++++++++++++++++

子元素的html:   1 <div class="box size">123123</div> 

absolute + 负marginsize

 1 /* 此处引用上面的公共代码 */
 2 /* 此处引用上面的公共代码 */
 3 
 4 /* 定位代码 */
 5 .wp {
 6     position: relative;
 7 }
 8 .box {
 9     position: absolute;;
10     top: 50%;
11     left: 50%;
12     margin-left: -50px;
13     margin-top: -50px;
14 }

absolute + margin auto

 1 /* 此处引用上面的公共代码 */
 2 /* 此处引用上面的公共代码 */
 3 
 4 /* 定位代码 */
 5 .wp {
 6     position: relative;
 7 }
 8 .box {
 9     position: absolute;;
10     top: 0;
11     left: 0;
12     right: 0;
13     bottom: 0;
14     margin: auto;
15 }

absolute + calc

 1 /* 此处引用上面的公共代码 */
 2 /* 此处引用上面的公共代码 */
 3 
 4 /* 定位代码 */
 5 .wp {
 6     position: relative;
 7 }
 8 .box {
 9     position: absolute;;
10     top: calc(50% - 50px);
11     left: calc(50% - 50px);
12 }

++++++++ 不固定高度宽度 移除css类size +++++++++++++++++

absolute + transform

 1 /* 此处引用上面的公共代码 */
 2 /* 此处引用上面的公共代码 */
 3 
 4 /* 定位代码 */
 5 .wp {
 6     position: relative;
 7 }
 8 .box {
 9     position: absolute;
10     top: 50%;
11     left: 50%;
12     transform: translate(-50%, -50%);
13 }

lineheight

 1 /* 此处引用上面的公共代码 */
 2 /* 此处引用上面的公共代码 */
 3 
 4 /* 定位代码 */
 5 .wp {
 6     line-height: 300px;
 7     text-align: center;
 8     font-size: 0px;
 9 }
10 .box {
11     font-size: 16px;
12     display: inline-block;
13     vertical-align: middle;
14     line-height: initial;
15     text-align: left; /* 修正文字 */
16 }

css-table

1 .wp {
2     display: table-cell;
3     text-align: center;
4     vertical-align: middle;
5 }
6 .box {
7     display: inline-block;
8 }

flex

1 .wp {
2     display: flex;
3     justify-content: center;
4     align-items: center;
5 }

grid

1 .wp {
2     display: grid;
3 }
4 .box {
5     align-self: center;
6     justify-self: center;
7 }

总结


下面对比下各个方式的优缺点,肯定又双叒叕该有同学说回字的写法了,简单总结下

  • PC端有兼容性要求,宽高固定,推荐absolute + 负margin
  • PC端有兼容要求,宽高不固定,推荐css-table
  • PC端无兼容性要求,推荐flex
  • 移动端推荐使用flex


原文地址:https://www.cnblogs.com/feixiablog/p/9646311.html