width height定

1.绝对定位 top50% left50% margin-top 负值定为自身高一半 margin-left负值定为自身宽一半

2.定位拉伸 定位父relative子absolute top0 left0 right0 bottom0 margin auto

      .box {
            width: 300px;
            height: 300px;
            background-color: aquamarine;
            position: relative;
        }

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

width height不定 尺寸不固定

1.兼容性很好 只有ie老版本不兼容因为display:inline-block没有

水平居中 text-align: center;

垂直居中 利用伪元素

    .box::after {
            content: "";
            display: inline-block;
            height: 100%;
            vertical-align: middle;
        }

 <style>
          .box {
            width: 300px;
            height: 300px;
            text-align: center;
            background-color: aquamarine;
        }

        .pinx_box {
            width: 100px;
            height: 80px;
            background-color: pink;
            display: inline-block;
            vertical-align: middle;
        }

        .box::after {
            content: "";
            display: inline-block;
            height: 100%;
            vertical-align: middle;
        }
    </style>

<body>
    <div class="box">
        <div class="pinx_box"></div>
    </div>
</body>

2. 弹性很好 兼容性不好

父容器包裹起来 给父容器设置

3.IE>=9才能用 

利用left top百分比是相对于父元素的,translate百分比是相对于自身的。

好了本篇文章就到这里了,喜欢的话可以关注我,会持续更新的,有错误欢迎大家指出,大家可以在我这里互相讨论学习,一起进步。

青山不改 绿水长流 我们下篇文章见😋 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐