整理笔记5: CSS定位垂直居中对齐

148 阅读1分钟

CSS定位垂直居中对齐

我是knockkey, 这是我坚持更新博客第2天. 这篇博客的目的是解决: 垂直居中可太常用了呀

知识点:

水平居中

  inline元素: text-align:center
  block元素: margin:auto
  absolute元素: left:50% + margin-left 负值宽度的一半 (必须要知道子元素宽)

垂直居中

  inline元素:line-height的值等于height值
  absolute元素: top:50% + margin-top负值高度的一半 (必须要知道子元素高)
  absolute元素:transform(-50%,-50%) (注意浏览器兼容CSS3的问题)
  absolute元素:top, left, bottom, right=0 + margin:auto (直接无敌, 既不需要考虑浏览器兼容又不需要知道子元素的宽高)

代码展示

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      border: 1px solid rgb(199, 0, 0);
      margin: 10px;
      padding: 10px;
      height: 200px;
    }

    .item {
      background-color: #ccc;
    }

    .container-1 {
      /* 行内水平居中 */
      text-align: center;
      /* 垂直居中 */
      line-height: 200px;
      height: 200px;

    }

    .container-2 {
      position: relative;
    }

    .container-2 .item {
      width: 300px;
      height: 100px;

      position: absolute;
      /* 水平居中 */
      left: 50%;
      margin-left: -150px;
      /* 垂直居中 */
      top: 50%;
      margin-top: -50px;
    }

    .container-3 {
      position: relative;
    }

    .container-3 .item {
      width: 200px;
      height: 80px;
      position: absolute;
      /* 水平垂直 */
      left: 50%;
      top: 50%;
      /* 上面此时 左上角在正中央 我要拉回来 transform css3的属性, 注意兼容问题  */
      transform: translate(-50%, -50%);
    }

    .container-4 {
      position: relative;
    }

    .container-4 .item {
      width: 100px;
      height: 50px;
      position: absolute;
      /* 水平垂直 */
      /* 既保证了浏览器的兼容性, 又保证了子元素的宽高是未知的 */
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      margin: auto;
    }
  </style>
</head>

<body>
  <!-- 1 -->
  <div class="container container-1">
    <span>一段文字</span>
  </div>
  <!-- 2 -->
  <div class="container container-2">
    <div class="item">
      this is item
    </div>
  </div>
  <!-- 3 -->
  <div class="container container-3">
    <div class="item">
      this is item
    </div>
  </div>
  <!-- 4 -->
  <div class="container container-4">
    <div class="item">
      this is item
    </div>
  </div>

</body>

</html>