css塊級居中的四種方法


HTML

 

<div class="fater">
    <div class="sum"></div>
</div>

方式一: 父級相對 子級絕對

  要求子級寬度設置

<style>
    .fater{
        width: 500px;
        height: 500px;
        border: 1px solid black;
        position: relative;
    }
    .sum{
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -50px;
        margin-top: -50px;
    }
</style>

方式二:transform:translate(-50%);

  寬高不確定,transform是css3屬性注意兼容性問題

<style>
    .fater{
        width: 500px;
        height: 500px;
        border: 1px solid black;
        position: relative;
    }
    .sum{
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%);
    }
</style>

方式三

  子級寬高不確定

<style>
    .fater{
        width: 500px;
        height: 500px;
        border: 1px solid black;
        position: relative;
    }
    .sum{
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }
</style>

方式四:flex布局

<style>
    .fater{
        width: 500px;
        height: 500px;
        border: 1px solid black;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .sum{
        width: 100px;
        height: 100px;
        background: red;
    }
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM