css position屬性爲absolute時,其百分值的計算

當position爲absolue時候,其相關屬性的百分比是相對它參考的元素(包含塊)來進行計算並進行位置渲染的 。
首先咱們必須知道:
一、[百分比的參照][1]:
根據包含塊計算百分值 (1)元素的margin/padding/left/right/width參照包含塊的width來計算;(2)要計算 height /top 及 bottom 中的百分值,是經過包含塊的 height 的值。若是包含塊的 height 值會根據它的內容變化,並且包含塊的 position 屬性的值被賦予 relative 或 static ,那麼,這些值的計算值爲 0。
二、[肯定包含塊][2]:
肯定一個元素的包含塊的過程徹底依賴於這個元素的 position 屬性:
(1)若是 position 屬性爲 static 或 relative ,包含塊就是由它的最近的「祖先塊元素」(好比說inline-block, block 或 list-item元素)或格式化上下文(好比說 a table container, flex container, grid container, or the block container itself)的內容區的邊緣(content)組成的。
(2)若是 position 屬性爲 absolute ,包含塊就是由它的最近的 position 的值不是 static (也就是值爲fixed, absolute, relative 或 sticky)祖先元素的內邊距區的邊緣(padding-left + content + padding-right)組成。
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
     body {
  color: orange;
}
div {

  position: absolute; 
  /*box-sizing: border-box; /*加box-sizing: border-box;時的content=(width-border-padding);未加時的width=content*/*/
  width: 400px;
  border: 5px solid orange;
  padding: 50px;
  height: 160px;
  background: lightgray;
}

p {
  position: absolute; /* 包含塊爲最近的祖先元素(多是塊也可能不是塊元素)的內邊距邊緣(padding-left + content + padding-right)組成;
  width: 50%;   /* == (50+400+50)px * 50% = 250px */
  height: 25%;  /* == (50+160+50)px * 25% = 65px */
  margin: 5%;   /* == (50+400+50)px * 5% = 25px */
  border: 5px solid orange;
  padding: 5%;  /* == (50+400+50)px * 5% = 25px */
  background: pink;
  color: green;
}
/*p {
   /* 包含塊爲最近的祖先塊元素(只能是塊元素)或格式化上下文的內容區的邊緣(content)組成;
  width: 50%;   /* == 400px * 50% = 200px */
  height: 25%;  /* == 160px * 25% = 40px */
  margin: 5%;   /* == 400px * 5% = 20px */
  border: 5px solid orange;
  padding: 5%;  /* == 400px * 5% = 20px */
  background: pink;
  color: green;
}*/
    
    </style>
</head>
<body>
    <div>
        <p>This is a paragraph!</p>
    </div>
</body>
</html>

圖片描述圖片描述

相關文章
相關標籤/搜索