美文网首页网页前端后台技巧(CSS+HTML)
关于使用css使得div完美居中的方法

关于使用css使得div完美居中的方法

作者: 呼小鹏 | 来源:发表于2020-03-24 11:18 被阅读0次
    <style>
    /* 父元素 */
    .bigBox{
        width: 800px;
        height: 600px;
        border: 1px solid #000;
    }
    /* 子元素 */
    .smallBox{
        width: 300px;
        height: 200px;
        border: 1px solid red;
    }
    /* 方法1  position定位 */
    .bigBox1{
        position: relative;
    }
    .smallBox1{
        position: absolute;
        left: 50%;
        margin-left: -150px;
        top: 50%;
        margin-top: -100px;
        text-align: left;
    }
    /* 方法2  css3 flex方法 */
    .bigBox2{
        display: flex;
    }
    .smallBox2{
        text-align: center;
        margin: auto;
    }
    /* 方法3   css3display方法,box-pack和box-align是关键  */
    .bigBox3{
        /* Internet Explorer 10 */
        display:-ms-flexbox;
        -ms-flex-pack:center;
        -ms-flex-align:center;
    
        /* Firefox */
        display:-moz-box;
        -moz-box-pack:center;
        -moz-box-align:center;
    
        /* Safari, Chrome, and Opera */
        display:-webkit-box;
        -webkit-box-pack:center;
        -webkit-box-align:center;
    
        /* W3C */
        display:box;
        box-pack:center;
        box-align:center;
    }
    .smallBox3{
        text-align: right;
    }
    /* 方法4   与方法1类似,用了css3的calc计算,符号左右为空格 */
    .bigBox4{
        position: relative;
    }
    .smallBox4{
        position: absolute;
        left: calc(50% - 150px);
        top: calc(50% - 100px);
    }
    /* 方法5 */
    .smallBox5{
        position: absolute;
        left: 50%;
        top: 50%;
            transform: translate(-50%, -50%);
    }
    </style>
    
    <div class="bigBox bigBox1">              <!-- 以下五种方法都可以实现div完美居中 -->
        <!-- <div class="smallBox smallBox1">small1</div>
        <div class="smallBox smallBox2">small2</div> 
        <div class="smallBox smallBox3">small3</div> -->
        <div class="smallBox smallBox4"></div>
            <div class="smallBox smallBox5"></div>
    </div>
    
    
    
    实际使用中人们可以按照实际情况使用不同的方法来实现居中。
    例如:margin和padding的%也可以实现效果。
    写出来只为记录和学习。
    div居中是前端面试比较常问的问题,不过在我看来是一些幼稚前端的自娱自乐罢了,实际开发中使用的场景并不是很多。
    (也是有些面试的人真的把各种各样div居中当成css熟练程度的标准)

    相关文章

      网友评论

        本文标题:关于使用css使得div完美居中的方法

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