位置绝对和固定块元素如何获得尺寸?

时间:2020-07-09 15:14:11

标签: html css

实际上我看到了很多这样的问题,但是我找不到这个问题的正常答案,因为我再次打开了这个问题。

当具有块元素(显示:块)时,如果元素本身是根元素,则此元素包含父组件的完整宽度。

但是当我们查看块元素(display:block)但定位绝对元素时,甚至有内联块元素(像块元素一样工作,但宽度未充满父组件)甚至父元素相对位置也起作用。

谁能解释我为什么绝对位置和固定元素宽度不能像显示那样工作:块元素。

https://jsfiddle.net/epbkmzh3/28/

  val vec_of_elements = Vec(10, Module(SaturatingCounter(4)).io)

2 个答案:

答案 0 :(得分:4)

这是因为absolutefixed定位从文档流中删除了元素。

并且由于这些元素已从文档流中删除,因此没有关于其应具有的宽度的参考,因此它们仅占用其内容所需的空间。

如果它们本质上是块元素(divp等),它们仍然是“块”元素,除非通过CSS更改了display属性。 为清晰起见:即使通过CSS更改了display属性,浏览器仍将以display: block进行计算。

以下是有关文档流程的一些文档: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/In_Flow_and_Out_of_Flow

重要的部分:

Taking an item out of flow

All elements are in-flow apart from:

    floated items
    items with position: absolute (including position: fixed which acts in the same way)
    the root element (html)

Out of flow items create a new Block Formatting Context (BFC) and therefore everything inside them can be seen as a mini layout, separate from the rest of the page. The root element therefore is out of flow, as the container for everything in our document, and establishes the Block Formatting Context for the document.

答案 1 :(得分:1)

以下是规范,其中详细介绍了如何找到任何元素的宽度/高度:https://www.w3.org/TR/CSS21/visudet.html

从那里您可以阅读以下绝对元素:

确定这些元素的使用值的约束是:

'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block

然后

如果“ left”,“ width”和“ right”的全部三个均为“ auto”:首先将“ margin-left”和“ margin-right”的任何“ auto”值设置为0。然后,如果建立静态位置包含块的元素的“ direction”属性为“ ltr”,将“ left”设置为静态位置,并在下面应用规则三;否则,将“ right”设置为静态位置,然后应用以下第一条规则。

第三个规则:

'width'和'right'为'auto'而'left'不是'auto',则宽度为fit-fit 。然后解决“正确”

第一条规则也很相似

如果您继续阅读,将会发现如何计算缩小以适应的宽度。您还将注意到,相同的缩小以适应算法适用于floatinline-block元素


还请注意,固定元素是绝对值的特殊情况,因此适用相同规则。唯一的区别是包含块

固定定位是绝对定位的子类别。唯一的区别是,对于固定位置的框,包含块是由视口建立的。 ref


您还可以看到,块元素遵循几乎相同的约束(无左/右),但the rules are different

其他属性的使用值中必须包含以下约束:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

然后

如果将“宽度”设置为“自动”,则其他所有“自动”值将变为“ 0”,并且从产生的相等性中得出“宽度”。

这将使width = width of containing block


内联块元素之间的一个重要区别是,绝对元素不会像我们认为的那样占用其内容的宽度。由于上述约束,在大多数情况下会发生这种情况,但请检查以下示例:

.container {
 clear:left;
 margin:5px;
}
<div class="container" style="float:left;position:relative;">
  <div style="display:inline-block; background: red;"> 1 1 1 1 1 1  </div>
</div>

<div class="container" style="float:left;position:relative;">
  <div style="position: absolute; background: red;"> 1 1 1 1 1 1  </div>
</div>

请注意,绝对元素将如何包装到尽可能小的尺寸,以使内联块脱线。这是由于包含块也是缩小以适合容器的事实。

相关:Why everything word-wrap inside an absolute element nested inside a float or inline-block element

相关问题