Is there a parent child relationship between absolute and relative positioning in CSS?

Pea*_*key 15 html css

I am new to the world of coding as well as CSS. Having read a number of articles regarding relative and absolute positioning, my understanding is as follows. However, I am unsure if an absolute position should be the child of a parent relative position or vice versa.

  • There are 4 position properties, that is, static, relative, absolute and fixed.
  • If an element has a relative position it is still part of the normal flow of the document. However, it has the ability to be offset by the properties top, right, bottom and left.
  • It also is able to be given a z-index value and is automatically positioned above static elements
  • It also provides a method of containing child elements that are part of its code block although I am unsure exactly what this means.

Based on this information, does this mean that elements with the position absolute should be children of elements with the position relative or vice versa or does it not matter?

If it does not matter, when would you make them dependent upon one another e.g. parent-child relationship?

joe*_*rdi 15

没有真正的亲子关系.

相对定位与绝对定位无关.相对定位与普通静态定位相同,只是它可以偏移顶部/右侧/底部/左侧,如您所解释的那样."顶部/右侧/底部/左侧"值相对于元素通常存在于流中的任何位置.如果省略这些值,元素仍然处于相对位置,但其位置与静态定位完全相同.

OTOH,当你使用绝对定位时,绝对定位元素的"父"元素很重要.

这是因为LaC的答案解释了这一点.对于绝对定位,"顶部/右侧/底部/左侧"值相对于具有绝对,相对或固定定位的最近父元素.我将其称为"参考元素".

考虑这个示例片段:

<body>
  <div style="width: 50%;">
    <p style="position: absolute; width: 20px; top: 0; right: 0">P</p>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

div将左对齐,静态(正常,在文档流程中)位置,50%的正文宽度.p将是一个20px宽的框,位于视口的右上角:

-------------
|     |   |P|
|     |   --|
| div |     |
|     |     |
|     |     |
-------------
Run Code Online (Sandbox Code Playgroud)

视口是引用元素,因为p中没有其他父元素具有绝对/固定/相对定位.

现在将div更改为相对定位:

<body>
  <div style="position: relative; width: 50%;">
    <p style="position: absolute; width: 20px; top: 0; right: 0">P</p>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

div将与之前完全相同,因为没有指定顶部/右侧/底部/左侧偏移.然而,即使它的风格没有,p的位置也会改变.

这是因为,之前,p与视口的右上角对齐,但现在有一个更接近的父元素(div)具有绝对/固定/相对定位.所以现在,div成为参考元素,p将与其右上角对齐:

-------------
|   |P|     |
|   --|     |
| div |     |
|     |     |
|     |     |
-------------
Run Code Online (Sandbox Code Playgroud)

所以,只要知道无论何时使用绝对定位,都必须考虑文档中的参考元素是什么.而且,您可以设计样式表,以便选择此参考元素,这使绝对定位成为非常有用的布局技术.


LaC*_*LaC 6

绝对定位是相对于具有绝对,相对或固定定位的最近祖先.有时,给元素相对定位只是为了建立一个新的参考框架来定位其子项的绝对定位是有用的.

  • 假设你在页面上有一个div.它具有top,left = 0,0的绝对定位,并且它的所有祖先(即包含它的元素,直到页面主体)具有正常定位(不是绝对的,相对的或固定的).然后div显示在页面的左上角.现在让我们说你有一个div绝对定位在300,100,而另一个div在它内部绝对定位在50,50.然后第一个div相对于页面为300,100,第二个相对于第一个div为50,50,这意味着它相对于页面为350,150. (4认同)