1-10、手写垂直水平居中

73 阅读1分钟

常见的垂直水平居中方法

1. position + margin负值的方法(宽高固定)

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        position: relative;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item{
        position: absolute;
        left: 50%;
        top: 50%;
        margin-top: -150px;
        margin-left: -100px;
        width: 200px;
        height: 300px;
        background-color: #ccc;
    }
</style>

<body>
    <div class="box">
        <div class="item">@包子枫的枫 - bilibili</div>
    </div>
</body>

2.position + margin:auto(固定宽高)

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        position: relative;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item{
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        width: 200px;
        height: 300px;
        background-color: #ccc;
    }
</style>

<body>
    <div class="box">
        <div class="item">@包子枫的枫 - bilibili</div>
    </div>
</body>

3.display:table-cell + vertical-align:middle(固定宽高)

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        display: table-cell;
        vertical-align: middle;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item{
        width: 200px;
        margin: auto;
        height: 300px;
        background-color: #ccc;
    }
</style>

<body>
    <div class="box">
        <div class="item">@包子枫的枫 - bilibili</div>
    </div>
</body>

4.position + transform(不需要固定宽高)

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        position: relative;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item{
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
        width: 200px;
        height: 300px;
        background-color: #ccc;
    }
</style>

<body>
    <div class="box">
        <div class="item">@包子枫的枫 - bilibili</div>
    </div>
</body>

5.flex(不需要固定宽高)

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        /* 在父级上设置flex */
        display: flex;
        /* 子级垂直水平居中与父级 */
        justify-content: center;
        align-items: center;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }

    .item {
        /* 有没有宽高都可以实现垂直水平居中 */
        width: 200px;
        height: 300px;
        background-color: #ccc;
    }
</style>

<body>
    <div class="box">
        <div class="item">@包子枫的枫 - bilibili</div>
    </div>
</body>

image.png