css position属性为absolute时其百分值的计算

Carol ·
更新时间:2024-09-21
· 605 次阅读

当position为absolue时候,其相关属性的百分比是相对它参考的元素(包含块)来进行计算并进行位置渲染的 。

首先我们必须知道:

1、[百分比的参照][1]:

根据包含块计算百分值(1)元素的margin/padding/left/right/width参照包含块的width来计算;(2)要计算 height /top 及 bottom 中的百分值,是通过包含块的 height 的值。如果包含块的 height 值会根据它的内容变化,而且包含块的 position 属性的值被赋予 relative 或 static ,那么,这些值的计算值为 0。

2、[确定包含块][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>



absolute position CSS

需要 登录 后方可回复, 如果你还没有账号请 注册新账号