各种居中方法梳理

 1.移动端的flex大法:

1  .parent{
2    display:flex;
3    flex-flow:row wrap;
4    justify:content:center;
5    //单行时
6    align-items:center;
7    //多行时:
8    align-content:center;
9  }

相关兼容问题:https://www.zhihu.com/question/29924791

2.margin left/right设置为auto:

1 .child{
2 margin:0 auto;
3 }

浮动/绝对定位时无效,流式布局中用的比较多。

3.行内对齐:

1 .parent{
2   //在ie6、7中对块级也有效
3   text-alig:center;
4 }

4.单行文字居中对齐:

1 .child{
2   //让行高等于文字容器高度即可
3   line-height:container's height;
4 }

  多行文本时,用一个div把文本包裹,看作一个整体进行居中即可。

5.表格:

使用表格时,只要将td的align:center,valign:middle 即可。如果要在css中写居中样式:vertical-align:middle;text-align:center;

注意:IE8以上的浏览器text-align:center;只对行内元素起作用。

6.模拟表格布局:

 1 .parent{
 2   display:table-cell;
 3   vertical-align:middle;
 4   text-align:center;
 5   height:400px;
 6   width:400px;
 7 }
 8 .child{
 9   height:200px;
10   width:200px;
11   background-color:black;
12   display:inline-block;
13 }

此法只对ie8以上有效。

7.纯绝对定位居中:

用绝对定位top、left设置50%,用元素高/宽的一半补偿。

 1 .parent{
 2 position:relative;
 3   height:400px;
 4   width:400px;
 5 }
 6 .child{
 7   position:absolute;
 8   top:50%;
 9   left:50%;
10   margin-left:-100px;
11   margin-top:-100px;
12   height:200px;
13   width:200px;
14   background-color:black;
15 }

在已知元素高/宽的时候使用。

8.另一种绝对定位(IE9+)

 1 .parent{
 2   position:relative;
 3   height:400px;
 4   width:400px;
 5 }
 6 .child{
 7   position:absolute;
 8   top:0;
 9   left:0;
10   right:0;
11   bottom:0;
12   margin:auto;
13   height:200px;
14   width:200px;
15   background-color:black;
16 }

如果不设置高宽的话,元素会填充整个容器。

9.浮动+相对定位 实现水平居中:

将浮动元素相对定位到父元素宽度的50%,浮动元素的子元素再相对之定位-50%补偿一半宽度,实现居中。不必知道元素的宽度。

.parent{
  height:400px;
  width:400px;
}
.wrapper{
  float:left;
  position:relative;
  left:50%;
  border:1px solid black;
  clear:both;
}
.pat{
  position:relative;
  left:-50%;
  width:100px;
  height:100px;
  background-color: red;
}

10.绝对定位+transform

 1 .parent{
 2   height:400px;
 3   width:400px;
 4   position:relative;
 5 }
 6 .child{
 7   position:absolute;
 8   left:50%;
 9   top:50%;
10   transform:translate(-50%,-50%);
11   background-color:black;
12   width:100px;
13   height:100px;
14 }

这是我移动端上比较常用的一种.

 

posted @ 2017-09-03 10:20  瓶子2333  阅读(187)  评论(0编辑  收藏  举报