Css中常用的居中整理

2023-03-29  本文已影响0人  不老歌_Bloger

方法一、通过top和margin-top

<style>
    .box {
        width: 100%;
        height: 500px;
        background: red;
        position: relative;
    }
    .content {
        width: 200px;
        height: 200px;
        background: green;
        margin: 0 auto; /*水平居中*/
        position: absolute;
        top: 50%;
        margin-top: -100px;
        left: 50%;
        margin-left: -100px;
    }
</style>

方法二、通过top和transform

<style>
    .box {
        width: 100%;
        height: 500px;
        background: red;
        position: relative;
    }
    .content {
        width: 200px;
        height: 200px;
        background: green;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
</style>

or

<style>
    .box {
        width: 100%;
        height: 500px;
        background: red;
    }
    .content {
        width: 200px;
        height: 200px;
        background: green;
        position: relative;
        top: 50%;
        transform: translateY(-50%);
        margin: 0 auto;
    }
</style>

方法三、使用display、align-items和justify-content

<style>
    .box {
        width: 100%;
        height: 500px;
        background: red;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .content {
        width: 200px;
        height: 200px;
        background: green;
    }
</style>
上一篇 下一篇

猜你喜欢

热点阅读