css垂直居中显示

101 阅读1分钟

1.使用定位+transform(常用于宽高未知)

html

  <div class="father">
    <div class="son"></div>
  </div>

css

    .father {
      width: 500px;
      height: 500px;
      background-color: green;
      position: relative;
    }
    .son {
      width: 50px;
      height: 50px;
      background-color: red;
      position: absolute;
      top:50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }

2.使用绝对定位

html

 <div class="father">
    <div class="son"></div>
  </div>

css

    .father {
      width: 500px;
      height: 500px;
      background-color: green;
      position: relative;
    }
    .son {
      width: 50px;
      height: 50px;
      background-color: red;
      position: absolute;
      top:0;
      left:0;
      right: 0;
      bottom: 0;
      margin: auto;
    }

将上下左右的数值都设置0,同时margin:auto。绝对定位是会脱离文档流的。

3.使用display:flex(常用于宽高位置)

html

 <div class="father">
    <div class="son"></div>
  </div>

css

    .father {
      width: 500px;
      height: 500px;
      background-color: green;
      display: flex;
      /* 两端 */
      justify-content: center;
      /* 上下 */
      align-items: center;
    }
    .son {
      width: 50px;
      height: 50px;
      background-color: red;
    }

水平居中:justify-content;垂直居中:align-items

4.使用行高(适用于文字)

html

  <div class="father">
    <span class="son">你好</span>
  </div>

css

    .father {
      width: 500px;
      height: 500px;
      background-color: green;
    }
    .son {
      width: 500px;
      line-height: 500px;//垂直居中
      text-align: center; //水平居中
      color: red;
      display: inline-block;//行内元素转化为内联块状元素
    }

5.使用absolute+calc

html

  <div class="father">
    <div class="son"></div>
  </div>

css

    .father {
      width: 500px;
      height: 500px;
      position: relative;
      background-color: green;
    }

    .son {
      width: 50px;
      height: 50px;
      position: absolute;
      background-color: red;
      top: calc(50% - 25px);
      left: calc(50% - 25px);
    }

calc()函数用于动态计算长度值 运算符前后都需要保留一个空格

6.使用display:table-cell实现css垂直居中(常用于宽高位置)

html

<div class="father">
  <span class="son">你好</span>
</div>

css

    .father {
      width: 500px;
      height: 500px;
      background-color: green;
      /* 作为块级表格来显示 <table>*/
      display: table;
    }

    .son {
      /* 作为一个表格单元格显示 <th>和<td>*/
      display: table-cell;
      /* 垂直居中 */
      vertical-align: middle;
      /* 水平居中 */
      text-align: center;
    }

父元素display:table;子元素:table-cell会自动撑满父元素