javascript - absolute和relative的区别很大?
ringa_lee
ringa_lee 2017-04-10 15:30:12
[JavaScript讨论组]

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

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



<p class="p1"> <p class="p2"> <p class="p3"></p> <p class="p4"></p> </p> </p> .p1{ border:3px solid red; position:absolute; } .p2{ background:yellow; width:200px; } .p3{ float:left; width:50px; height:300px; background:orange; } .p4{ width:100px; height:100px; background:blue; }
ringa_lee
ringa_lee

ringa_lee

全部回复(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属性的元素定位的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号