html塊級元素的水平垂、直居中的方式


說明

對於初學者來說,塊級元素的劇中,也是一大難題,我學習的時候,也是一臉懵逼,每次遇到都要百度,但是寫的多了也自然記住一些常用的劇中方式,但是還是很模糊,今天就來好好總結一些。

布局

布局即為簡單,一個div套着一個div,使inner1在wrap居中顯示。

 <body>
     <div id="wrap">
         <div class="inner1"></div>
     </div>
 </body>

水平劇中

  • margin: 0 auto;

    子元素的寬度小於父元素,不然子元素寬度等於父元素寬度,就沒意義了。

 #wrap{
    width: 500px;
    height: 500px;
    margin: 0 auto;
    background-color: red;
 }
			
  #wrap .inner1{
    width: 100px;
    height: 100px;
    margin: auto;
    background-color: blue;
 }
  • 絕對定位 + 負外邊距

    一開始我也不理解,看圖一,當子元素left: 50%;它會以父元素為參照,定位到left值為父元素寬度的一半,如圖1的有圖,可以看到在將子元素向左移動自身寬度的一半即可水平劇中,因此加上margin-left: 50px;

 #wrap{
    width: 500px;
    height: 500px;
    margin: 0 auto;
    position: relative;
    background-color: red;
 }
			
  #wrap .inner1{
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    margin-left: -50px;
    background-color: blue;
 }

  • 絕對定位 + translateX

    上面的方式,有一個缺點,子元素高寬度要知道,但是兼容性好,transform為CSS3新屬性,因此有兼容性問題,但是它不需要知道高度值。

 #wrap{
    width: 500px;
    height: 500px;
    margin: 0 auto;
    position: relative;
    background-color: red;
 }
			
  #wrap .inner1{
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    background-color: blue;
 }

垂直居中

  • 絕對定位 + margin: auto 0;

    具體什么原理,我也不是很了解。設置top、bottpm為相同的值,不一定是 0,上下外邊距auto即可。

 #wrap{
    width: 500px;
    height: 500px;
    margin: 0 auto;
    position: relative;
    background-color: red;
 }
			
  #wrap .inner1{
    width: 100px;
    height: 100px;
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto 0;
    background-color: blue;
 }
  • 絕對定位 + translateY

    原理與上面的水平居中:絕對得 + translateX的方式一樣。

 #wrap{
    width: 500px;
    height: 500px;
    margin: 0 auto;
    position: relative;
    background-color: red;
 }
			
  #wrap .inner1{
    width: 100px;
    height: 100px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: blue;
 }

注意

上面只是把水平、垂直居中分開來舉例,想要實現水平垂直居中,只要把相應的結合在一起即可。另外我們還可以使用flex布局,實現水平、垂直居中,這里不再討論了。

  • 絕對定位 + margin實現水平、垂直居中
 //另外一種也如此
 #wrap{
    width: 500px;
    height: 500px;
    margin: 0 auto;
    position: relative;
    background-color: red;
 }
   			
  #wrap .inner1{
    width: 100px;
    height: 100px;
    position: absolute;
    //left、top設置為 50%
    top: 50%;
    left: 50%;
    //左、上邊距再往回拉自身寬度的一本即可
    margin-left: -50px;
    margin-top: -50px;
    background-color: blue;
 }


免責聲明!

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



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