根据 W3Schools ( http://www.w3schools.com/css/css_positioning.asp ):
相对定位元素通常用作绝对定位元素的容器块。
为什么是这样?有很好的例子吗?
根据 W3Schools ( http://www.w3schools.com/css/css_positioning.asp ):
相对定位元素通常用作绝对定位元素的容器块。
为什么是这样?有很好的例子吗?
一个很好的例子是当您想将某些内容定位到页面或“相对”于容器/div 时。
这是我的小提琴http://jsfiddle.net/doitlikejustin/RdWQ7/2/
这向您表明,如果绝对 div 不在“相对”div 内,则内容与文档正文对齐。
请注意,绿色的 div ( #box1
),其中position: relative
div 内部 ( #inner1
) 对齐顶部/右侧 INSIDE 的内部#box1
。
蓝色框(#box2
_ #box1
_position: relative
#inner2
body
#box1, #box2 {
width: 100px;
height: 100px;
color: white;
text-align: center;
line-height: 100px;
}
#box1 {
background: green;
position: relative;
}
#box2 {
background: blue;
}
#inner1, #inner2 {
width: 50px;
height: 50px;
top: 0;
right: 0;
position: absolute;
background: black;
opacity: 0.5;
color: white;
text-align: center;
line-height: 50px;
}
这是 Chris Coyier 写的一篇很好的文章……
具有相对定位的页面元素使您可以控制在其中绝对定位子元素。
来源:http ://css-tricks.com/absolute-positioning-inside-relative-positioning/
其他答案没有明确说明的是:
绝对定位是在最近的没有静态定位的祖先中测量出来的。给祖先相对定位只是达到这个目的的一种手段。它不必是相对的,它不能是静态的。
具有绝对位置的元素和
顶部:10px;
将距离其位置不是静态的最近祖先的顶部 10 个像素。
如果绝对定位元素不在相对元素中,那么当您使用值设置 top、left、right 或 bot 时,它会将绝对位置元素从 body 移动该值。这是什么意思?例如,如果您将绝对位置元素的属性 top 设置为 10px,它会将元素从屏幕顶部推 10 个像素。
如果绝对位置元素位于相对元素中,那么当您使用值设置 top、left、right 或 bot 时,它将将该绝对位置元素从该相对元素移动该值。这是什么意思?例如,如果您将绝对位置元素的属性 top 设置为 10px,它将将该元素从相对元素的顶部推 10 个像素。在那里您可以移动相对元素,其中绝对定位的元素将始终距离相对元素的顶部 10 个像素。