元素水平垂直居中三种方法实现

一. 简介

实现一个元素水平垂直居中的效果。

二. 实现

<body>
<img class="center">
</body>

方法一:(此方法适合宽高固定的)  

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

方法二: (此方法适合宽高不固定的元素)

.center {
    position: absolute;
    left: 0;
    top: 0;
    margin: auto;
    right: 0;
    bottom: 0;
}

方法三:(宽高不固定的元素,此方法缺点就是只能适配到ie9+)

.center{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
}


猜你喜欢

转载自blog.csdn.net/qq_35321405/article/details/80762896