浮动元素撑开父元素的区别

大家都知道position设置为absolute以及float定位会使元素脱离正常流,如果父元素没有设置高度的话,他们不会把父元素的高度撑开。对于float元素可以把父元素设置overflow:hidden或者其他可以为父元素创建BFC的方法来解决这个问题,但是为什么对于绝对定位的元素这些办法行不通呢?求指教

阅读 14.4k
3 个回答

W3C标准的算法里,float可能参与父级高度计算,但position:absolute;始终不参与父级计算。就是这样设计的,没辙:

W3C CSS2.1 10.6.3规定了未创建BFC的非替换块级元素的高度计算规则:

This section also applies to block-level non-replaced elements in normal flow when 'overflow' does not compute to 'visible' but has been propagated to the viewport.

If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0. If 'height' is 'auto', the height depends on whether the element has any block-level children and whether it has padding or borders:

The element's height is the distance from its top content edge to the first applicable of the following:

  1. the bottom edge of the last line box, if the box establishes a inline formatting context with one or more lines
  2. the bottom edge of the bottom (possibly collapsed) margin of its last in-flow child, if the child's bottom margin does not collapse with the element's bottom margin
  3. the bottom border edge of the last in-flow child whose top margin doesn't collapse with the element's bottom margin
  4. zero, otherwise

如上述分点,分项1定义了line-box撑高容器,分项2和3定义了常规流块级元素撑高容器(margin折叠与否的两种情况),否则为0。

W3C CSS2.1 10.6.7规定了创建了BFC的元素(block formatting context roots)的高度计算规则:

If it only has inline-level children, the height is the distance between the top of the topmost line box and the bottom of the bottommost line box.
If it has block-level children, the height is the distance between the top margin-edge of the topmost block-level child box and the bottom margin-edge of the bottommost block-level child box.
Absolutely positioned children are ignored, and relatively positioned boxes are considered without their offset. Note that the child box may be an anonymous block box.
In addition, if the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges. Only floats that participate in this block formatting context are taken into account, e.g., floats inside absolutely positioned descendants or other floats are not.

这里规则大致跟上方一样,不同点在于margin不再折叠和float高度参与计算。

总之呢,在“撑高父容器圈”里面没有绝对定位元素的地位。

positionabsolute的元素是相对于离他最近的position不为static的父级元素定位的,它不会占据父元素的空间,所以也不会撑起父级元素,这点和设置float的元素不一样,唯一的办法是给父级元素设置高度。

position没有float的设定吧?只有说把元素float设定为left还是right
我的理解是,float虽然脱离正常流,但还在父元素之内,但是绝对定位的话,是完全脱离正常流且脱离父元素了,你把left设为0top设为0,就知道,已经跑到页面的左上角去了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题