css水平垂直居中的种常用方法

108 阅读1分钟
<div class="wrap">
   <div class="content">要居中的内容</div>
</div>

1. absolute + 负margin

  • 这种方式要求居中元素固定宽高
.wrap {
    position: relative;
}
.content {
    width: 100px;
    height:100px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
}

2. absolute + margin auto

  • 这种方式要求居中元素固定宽高
.wrap {
    position: relative;
}
.content {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

3. absolute + calc

  • 此方法为css3计算属性,需要居中元素固定宽高
.wrap {
    position: relative;
}
.content {
    width: 100px;
    height: 100px;
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}

4. 定位 + transform

.wrap {
    position: relative;
}
.content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

5. flex布局

.wrap {
    display: flex;
    justify-content: center;
    align-items: center;
}