CSS 绝对与相对位置宽度和高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5323177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
absolute vs relative position width & height
提问by sandeep
i know what is absolute & relative position but some points are still not cleared to me. for reference
我知道什么是绝对位置和相对位置,但我仍然没有弄清楚一些要点。以供参考
css:
css:
.rel{
position:relative;
background:red;
}
.abs{
position:absolute;
background:blue;
}
html:
html:
<div class="rel">rel</div>
<div class="abs">abs</div>
now points are :
现在要点是:
relative div takes 100% width automatically but absolute div only takes content width. why?
when i give height 100% there is no effect in the relative div but absolute div takes 100% height. why?
when i give margin-top:30px it's shift absolute div also but when i give top:30px then only relative div shift. why?
when i don't give
top:0 , left:0
to the absolute div it's takes above div height. why?
相对 div 自动采用 100% 宽度,但绝对 div 仅采用内容宽度。为什么?
当我给高度 100% 时,相对 div 没有影响,但绝对 div 需要 100% 高度。为什么?
当我给 margin-top:30px 时,它也会移动绝对 div,但是当我给 top:30px 时,只有相对 div 移动。为什么?
当我不给
top:0 , left:0
绝对 div 时,它需要高于 div 高度。为什么?
回答by warmanp
Setting
position:absolute
removes the element in question from the normal flow of the document structure. So unless you explicitly set a width it won't know how wide to be. you can explicitly setwidth:100%
if that is the effect you're after.An element with
position:relative
on the whole behaves in the same way a normalposition:static
element does. Therefore, settingheight:100%
will have no effect unless the parent element has a defined height. In contrast absolute positioned elements are removed from the document flow so are free to adjust to whatever height their containing element currently has.This is probably something to do with the parent elements in your HTML but I can't help further unless you provide the full HTML and CSS of your page.
The default value of the top and left properties is auto. This means the browser will calculate these settings for you and set them to where the element would be rendered if it didn't have
position:absolute
.
设置
position:absolute
从文档结构的正常流中删除有问题的元素。因此,除非您明确设置宽度,否则它不会知道有多宽。您可以明确设置width:100%
这是否是您所追求的效果。与元素
position:relative
上以同样的方式正常整个的行为position:static
元素一样。因此,height:100%
除非父元素具有定义的高度,否则设置将不起作用。相比之下,绝对定位元素从文档流中删除,因此可以自由调整其包含元素当前具有的任何高度。这可能与 HTML 中的父元素有关,但除非您提供页面的完整 HTML 和 CSS,否则我无能为力。
top 和 left 属性的默认值是 auto。这意味着浏览器将为您计算这些设置,并将它们设置为如果元素没有
position:absolute
.