absolute和relative的区别很大?

1,为什么给absolute设置height:100%有作用,给relative设置的话就不会起作用?

2,absolute和relative对子类带有float的元素会有差异?
如果把div1换成relative就不会包裹div3,不知是为什么?



<div class="div1"> <div class="div2"> <div class="div3"></div> <div class="div4"></div> </div> </div> .div1{ border:3px solid red; position:absolute; } .div2{ background:yellow; width:200px; } .div3{ float:left; width:50px; height:300px; background:orange; } .div4{ width:100px; height:100px; background:blue; }
阅读 5k
4 个回答
  1. 定位参照元素的问题。
    absolute元素的定位参照元素为其父辈元素中第一个非static定位的元素,若其父辈元素均为static定位,则其定位参照元素为初始包含块,这里可以理解为 html 元素。
    设置height:100%100%是相对定位参照元素来说,因此为relative的元素设置100%不会产生效果,因为其相对body定位,而body的默认高度为0。而为absolute的元素设置100%产生效果是因为初始包含块的高度为 viewport 的高度。
    这里如果将 body 设置position: relative,则absoluterelative元素将具有相同的 height 表现

  2. BFC 问题。
    由于position:abolute会使当前块级元素称为一个 BFC 容器(通常称为触发 BFC),而包裹所有浮动元素是 BFC 容器的特性,position:abolute的元素可以包裹浮动元素而position:relative的元素不可以。有关 BFC 的详细内容可以参考我的博文:http://zjy.name/archives/bfc-introduction.html

absolute是绝对定位,定位是从left:0,top:0开始;relative是相对定位,判断定位是通过它的父级对象。要是相对定位和绝对定位组合使用的话,再根据具体情况再议。

1、有用:https://jsfiddle.net/dwqs/eond9m3y/

2、floatabsolute都会脱离文档流进行布局,而relative则不会脱离文档流,只是调整元素的位置。

float
The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container.

absolute
Do not leave space for the element. Instead, position it at a specified position relative to its closest positioned ancestor or to the containing block. Absolutely positioned boxes can have margins, they do not collapse with any other margins.

relative
This keyword lays out all elements as though the element were not positioned, and then adjust the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned).

relative 是相对父级定位, absolute 是相对上一个有relative属性的元素定位,而当元素的height:100%有没有效,是根据上一个相对的元素没有设置高度,从而决定当前的元素的height:100%有没有效。

如果当前元素被float,父级元素需要overflow: hidden;才会被撑开,或者用其他办法。

我说的有点乱,哈哈,其实很简单的,搞懂它们的特性就OK了。


原来是我的理解错了,是的,absolute 是根据上一个非static属性的元素定位的。

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