【CSS】css居中方案

  关于一些CSS居中的方案,先说一下水平居中和垂直居中的一般方案.

  水平居中设置:

  1. 行内元素:给父元素设置text-align:center;

  2. 定宽块状元素:设置左右margin值为auto

  3. 不定宽块状元素:

    1. 在元素外加入table标签(包括table、tbody、tr、td),在把该元素写在td内,然后设置margin的值为auto,注意是设置table不是该元素。

    2. 给该元素设置display:inline方法,居中方法和行内一致。

    3. 父元素设置float:left;position:relative和left:50%,子元素设置position:relative和left:-50%。

  垂直居中设置:

  1. 父元素高度确定的单行文本:设置height = line-height;

  2. 父元素高度确定的多行文本:

    1. 插入table(和水平居中一致),设置vertical-align:middle;

    2. 先设置display:table-cell,在设置vertical-align: middle;

  下面就提供几种居中的方法:

1.使用定位:position:absolute;设置left、top、margin-left、margin-top属性。

.content{
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
}

  这种方法好处是浏览器基本都能兼容,不足的地方就是需要我们固定宽高。

2.使用position: absolute;设置top、bottom、right、left为0,margin:auto;

.content {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    background-color: blue;    
}

3.使用display:table-cell属性使内容垂直居中。

.content {
      width: 100px;
      height: 100px;
      display: table-cell;
      vertical-align: middle;
      text-align: center;
}

4.使用css3的display:-webkit-box属性,在设置-webkit-box-pack:center/-webkit-box-align:center;

.content {
      width: 100px;
      height: 100px;
      display: -webkit-box;
      -webkit-box-pack: center;
      -webkit-box-align: center;
      background-color: blue;
}

5.使用css3的新属性transform:translate(x,y)属性。

.content {
      position: absolute;
      width: 100px;
      height: 100px;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      -webkit-transform: translate(-50%,-50%);
      -moz-transform:  translate(-50%,-50%);
      -ms-transform: translate(-50%,-50%);
      background-color: blue;
}
这种方法不需要设置固定宽高,移动端使用较多,移动端css3兼容的额比较好。

6.flex弹性布局。

.container {
      display: flex;
      justify-content: center; 
      align-items: center;
      width: 300px;
      height: 300px;
      background-color: red;
}
.content {
      width: 100px;
      height: 100px;
      background-color: blue;
}

  兼容性不是太好,ie10以下都挂掉了,而且webkit内核的浏览器必须设置为display: -webkit-flex;