根据W3Schools(http://www.w3schools.com/css/css_positioning.asp)的说法:
为什么会这样?有一个好的例子吗?相对定位元素经常用作绝对定位元素的容器块。
为什么会这样?有一个好的例子吗?相对定位元素经常用作绝对定位元素的容器块。
一个很好的例子是当你想把某个元素定位在页面上或者相对于一个容器/ div 时。
这是我的 Fiddle:http://jsfiddle.net/doitlikejustin/RdWQ7/2/
这表明,如果没有将绝对定位的 div 放在 "relative" 的 div 中,那么内容将与文档主体对齐。
请注意,绿色的 div (#box1
) 具有 position: relative
,里面的 div (#inner1
) 在 #box1
内部顶部/右侧对齐。
蓝色的盒子 (#box2
) 与绿色的盒子 (#box1
) 具有完全相同的 HTML 布局,但没有包含 position: relative
,请注意,在其中的 div (#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/
如果一个绝对定位的元素在相对元素中,那么当您设置top,left,right或bot属性时,它将按该值从相对元素中移动绝对定位元素。这是什么意思?例如,如果您将绝对定位元素的属性top设置为10px,则会将元素从相对元素顶部向下推动10像素。在此过程中,您可以移动相对元素,而其中的绝对定位元素始终距相对元素顶部10像素。
#box2
div将会像#inner2
一样移动到body内部。这里有一个例子http://jsfiddle.net/doitlikejustin/RdWQ7/3/我添加了`right`,这样你就可以看到它们之间的区别了。 - doitlikejustin