css 水平垂直居中

首先给定的结构如下: 

  <div class="red-box">
    <div class="blue-box"></div>
  </div>

方法1: 

      .red-box {
            position: relative;
            width: 500px;
            height: 300px;
            border: 1px solid red;
        }
        
        .blue-box {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            
            margin: auto;

            width: 300px;
            height: 200px;
            border: 1px solid blue;
        }

这个方法要注意 3 点:

  1. 绝对定位的 上右下左 的值是 0 ( 其实是可以设具体的值的, 具体效果可以自己动手试试 )

    这一步会使子元素撑满父元素

  2. 元素设置宽高, 不能大于父元素

  3. 设置 margin: auto; 这个是为了分配父元素剩余的空间, 实现居中

  

方法2: 

这个方法是使用 css3 的新特性实现居中:

translate 是根据元素自身的宽高

        .red-box {
            position: relative;
            width: 500px;
            height: 300px;
            border: 1px solid red;
        }

        .blue-box {
            position: absolute;
            top: 50%;
            left: 50%;

            transform: translate(-50%,-50%);
            
            border: 1px solid blue;
        }

方法3:

使用 css3 flex 布局实现居中

        .red-box {
            display: flex;
            align-items: center;
            justify-content: center;

            width: 500px;
            height: 300px;
            border: 1px solid red;
        }

        .blue-box {
            border: 1px solid blue;
        }

以上是我自己经常使用的居中方法, 这里只是做个简单的总结.

猜你喜欢

转载自www.cnblogs.com/xiangdong/p/8963530.html