1. 程式人生 > >元素水平垂直居中的方法

元素水平垂直居中的方法

1.父級相對定位,子級絕對定位

.parent{
    width: 500px;
    height: 500px;
    background: #f00;
    position: relative;
}
.child{
    width: 300px;
    height: 300px;
    background: #fff;
    position: absolute;
    top:50%;
    left: 50%;
    margin-left: -150px;
    margin-top: -150px;
}

2.元素寬度未知,

如果元素未知寬度,只需將上面例子中的margin-left: -150px;margin-top:-150px;替換為:transform: translate(-50%,-50%); 

.parent{
    width: 500px;
    height: 500px;
    background: #f00;
    position: relative;
}
.child{
    width: 300px;
    height: 300px;
    background: #fff;
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%,-50%); 
}

3.父級相對定位,子級絕對定位+margin:auto

.parent{
    width: 500px;
    height: 500px;
    background: #f00;
    position: relative;
}
.child{
    width: 300px;
    height: 300px;
    background: #fff;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

4.flex佈局

.parent{
    width: 500px;
    height: 500px;
    background: #f00;
    display: flex;
    justify-content: center;
    align-items: center
}
.child{
    width: 300px;
    height: 300px;
    background: #fff;
}

5.父級display:flex;子級margin:auto

.parent{
    width: 500px;
    height: 500px;
    background: #f00;
    display: flex;
}
.child{
    width: 300px;
    height: 300px;
    background: #fff;
    margin: auto;
}