絕對定位元素水平居中和垂直居中的原理


通常在設置絕對定位元素相對於其定位的祖先元素水平垂直居中時,通過絕對定位元素設置margin:auto; top:0; bottom:0; right:0; left:0;就可以實現。下面簡單探索一下絕對定位元素這么設置就可以實現水平居中和垂直居中的原理。

核心CSS代碼:

position:absolute;
margin:auto;
top:0;
bottom:0;
right:0;
left:0;

  

絕對定位元素的布局由元素的三個因素決定:位置(top、bottom、left、right)、元素尺寸和margin。絕對定位元素在布局上呈現自適應的特點——位置和尺寸固定,則自適應margin值;位置和margin固定,則自適應尺寸。

(1)位置和尺寸固定,margin:auto;

  <div id='wrap'>
    <div id='item1'></div>
  </div>

  

 #wrap {
      width: 500px;
      height: 500px;
      border: 1px dotted black;
      margin: 0 auto;
      position: relative;  
    }

    #item1 {
      width: 100px;
      height: 100px;
      background-color: purple;
      /* 核心代碼 */
      position: absolute;
      margin: auto;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
     
    }

布局效果:

計算樣式:

 

 

 

水平方向:

width(wrap)=margin(item)+width(item)+padding(item)+left(item)+right(item)

由於位置設置為 top: 0;bottom: 0;left: 0;right: 0; ,尺寸固定為 width: 100px;

height: 100px;,margin:auto;自適應,實際水平方向margin值為500-100 =400px,平均分配左右兩側,即為margin-left:200px;margin-right:200px;。垂直方向同理可得。可以看到在絕對定位元素中,若水平方向位置left與right值相等,那么margin-left: auto;margin-right:auto;可以讓其相對於定位的祖先元素水平居中。

(2)位置和margin固定

 <div id='wrap'>
    <div id='item1'></div>
  </div>

  

   #wrap {
      width: 500px;
      height: 500px;
      border: 1px dotted black;
      margin: 0 auto;
      position: relative;    
    }
    
    #item1 {
      background-color: purple;
      /* 核心代碼 */
      position: absolute;
      margin: 20px;
      top:0;
      bottom: 0;
      left: 0;
      right: 0;
    }

 布局效果

計算樣式

在水平方向,由於right:0;left:0;並且margin-left:20px;margin-right:20px;各項相加和等於定位的祖先元素寬度,因此width的值為460px。

其他情況:
如果同時設置top、bottom、left、right,margin設置值中沒有auto,那么位置top值優先於bottom值,left值優先於right值。

如果不設置位置,只設置margin:auto;那么布局中相當於margin:0;。

絕對定位元素和靜態定位元素的相互作用:
如果絕對定位元素存在靜態定位的兄弟元素,如果該元素沒有設置垂直位置,那么其垂直位置將以靜態定位的兄弟元素占位計算。

 <div id='wrap'>
    <div class='item2'>
    </div>
    <div id='item1'></div>
  </div>

  

 #wrap {
      width: 500px;
      height: 500px;
      border: 1px dotted black;
      margin: 0 auto;
      position: relative;
    }

    #item1 {
      width: 100px;
      height: 100px;
      background-color: purple;
      /* 核心代碼 */
      position: absolute;
      margin: auto;
     /*  top: 0px;
      bottom: 0; */
      left: 0;
      right: 0;

    }

    .item2 {
      width: 150px;
      height: 150px;
      background-color: green;
      position: static;
    }

  


免責聲明!

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



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