2012-05-07 77 views
291

我有另一个div内的两个div,我想定位一个子div到父div的右上角,另一个子div使用css的父div的底部。也就是说,我想对两个子div使用绝对定位,但将它们相对于父div而不是页面进行定位。我怎样才能做到这一点?绝对的位置,但相对于父母

样本HTML:

<div id="father"> 
    <div id="son1"></div> 
    <div id="son2"></div> 
</div> 
+0

你想SON1是在父亲的右上角但是在底部应该son2是什么?底部左,右,还是中心? – j08691

+0

在这种情况下,您需要设置位置:相对于父元素,以及位置:绝对值到子元素。在第一个子元素上,应该放置top:0和right:0以将其放置在父元素的右上角。在第二个孩子,你应该把底部:0放置在父元素的底部。 https://kolosek.com/css-position-relative-vs-position-absolute 详细解释了相对和绝对定位。 –

回答

541
#father { 
    position: relative; 
} 

#son1 { 
    position: absolute; 
    top: 0; 
} 

#son2 { 
    position: absolute; 
    bottom: 0; 
} 

这工作,因为position: absolute意味着类似“使用toprightbottomleft给自己定位有关谁拥有position: absoluteposition: relative最近的祖先“。

所以我们做#fatherposition: relative,和孩子们position: absolute,然后用topbottom给孩子定位。

+0

非常感谢。你能解释一下它是如何工作的吗?为什么? – BlaShadow

+4

为什么'#father {position:relative; '需要?需要 – joshreesjones

+1

来更改他内部人员的“职位规则”。 – BlaShadow

22
div#father { 
    position: relative; 
} 
div#son1 { 
    position: absolute; 
    /* put your coords here */ 
} 
div#son2 { 
    position: absolute; 
    /* put your coords here */ 
} 
+0

如果您需要调整父母与孩子的大小,该怎么办? – FrenkyB

5

如果您没有给予父母任何职位,那么默认情况下需要static。如果要明白,差参考本示例

实施例1 ::

http://jsfiddle.net/Cr9KB/1/

#mainall 
{ 

    background-color:red; 
    height:150px; 
    overflow:scroll 
} 

这里父类所以元件根据身体放置没有位置。

实施例2 ::

http://jsfiddle.net/Cr9KB/2/

#mainall 
{ 
    position:relative; 
    background-color:red; 
    height:150px; 
    overflow:scroll 
} 

在这个例子中具有父因此元件被定位相对母体内绝对相对位置。

+0

而且,如果您没有#mainall {height:150px} ...,怎么办?我的意思是,如果mainall有动态高度? –

+0

那么你的浮动元素将相对于父元素在加载页面(和css)时的位置。如果你想在页面加载后更新,使用javascript - clientX和clientY是一个很好的开始 –

2

柜面有人想现在的位置是一个孩子DIV直属父

#father { 
    position: relative; 
} 

#son1 { 
    position: absolute; 
    top: 100%; 
} 

工作演示Codepen

相关问题