使盒子水平垂直居中

89 阅读1分钟

定位写死

<style>
    .father {
        position: relative;
        
        width: 500px;
        height: 400px;
        background-color: pink;
    }
​
    .son {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-top: -100px;
        margin-left: -100px;
​
        width: 200px;
        height: 200px;
        background-color: purple;
    }
</style>
  
<div class="father">
    <div class="son"></div>
</div>

四测为0

<style>
    .father {
        position: relative;
        
        width: 500px;
        height: 400px;
        background-color: pink;
    }
​
    .son {
        position: absolute;
        margin: auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
​
        width: 200px;
        height: 200px;
        background-color: purple;
    }
</style>
  
<div class="father">
    <div class="son"></div>
</div>

利用transform

<style>
    .father {
        position: relative;
​
        width: 500px;
        height: 400px;
        background-color: pink;
    }
​
    .son {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
​
        width: 200px;
        height: 200px;
        background-color: purple;
    }
</style><div class="father">
    <div class="son"></div>
</div>

利用display: flex;

<style>
    .box {
        width: 500px;
        height: 400px;
        background-color: pink;
​
        display: flex;
        justify-content: center;
        align-items: center;
    }
​
    .box div {
        width: 200px;
        height: 200px;
        background-color: purple;
    }
</style><div class="box">
    <div>1</div>
</div>