美文网首页
Css中常用的居中整理

Css中常用的居中整理

作者: 不老歌_Bloger | 来源:发表于2023-03-29 11:08 被阅读0次

    方法一、通过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>
    

    相关文章

      网友评论

          本文标题:Css中常用的居中整理

          本文链接:https://www.haomeiwen.com/subject/berfddtx.html