實現水平垂直居中的幾種方法


水平居中

  1. 如果是行內元素,要實現水平居中只需要將父元素設置為text-align=center
  2. 如果是固定寬度的塊狀元素,設置該元素本身為margin: 0 auto
  3. css3的新屬性font-content,自動將元素寬度縮小到內容的寬度,然后使用margin:0 auto可以輕松的實現水平居中(目前只支持chrome和FireFox)

.son{ width: -moz-fit-content; width: -webkit-fit-content; width:fit-content; margin:0 auto; }

   4.絕對定位以及margin-left的負值實現水平居中

    

.son {
            position: absolute;
            width: 50px;
            left: 50%;
            margin-left: -25px;(寬度的一半)
            background-color: blue;
            text-align: center;
        }

   5.絕對定位left right同時設置為0 同時設置margin:0 auto

.son{
            position: absolute;
            width: 50px;
            left: 0;
            right: 0;
            background-color: blue;
            margin: 0 auto;
            height: 100%;
        }

垂直居中

  1. 若元素為單行文本,直接設置其text-align為父元素的高度
  2. 利用position以及top bottom屬性

 

.son{
    position:absolute;
    height:固定;
    top:0;
    bottom:0;
    margin:auto 0;
}

 

  3.利用margin的負值

.son{
    position:absolute;
    top:50%;
    height:固定;
    margin-top:-0.5高度;
}

  4.利用vertical-align

.parent::after, .son{
    display:inline-block;
    vertical-align:middle;
}
.parent::after{
    content:'';
    height:100%;
}

 


免責聲明!

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



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