Css中常用的居中整理

方法一、通过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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容