相对定位的div中的绝对底部定位

3

我希望将“rightBottomPart”定位到“rightPart”的底部,并且我希望“rightPart”与“leftPart”一样高。问题是我不知道“leftPart”中内容的高度,因此我无法设置“text”的高度。(在“text”中设置高度可以解决这个问题)

现在它看起来像这样:

alt text

我希望它看起来像这样:

alt text

我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
</head>
<body style="margin: 0px 0px 0px 0px;">
    <div id="headers" style="background-color: Olive; width: 300px; height: 50px;"></div>
    <div id="text" style="background-color: Navy; position: relative; width: 300px;">
        <div id="leftPart" style="background-color: Gray; width: 200px; float: left;">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
        <div id="rightPart" style="background-color: Red; float: right;">
                <div id="rightTopPart" style="background-color: Lime; position: absolute; right: 0px; top: 0px;">top</div>
                <div id="rightBottomPart" style="background-color: Yellow; position: absolute; right: 0px; bottom: 0px;">bottom</div>
        </div>
    </div>
</body>
</html>

在我测试的其他浏览器中,它看起来只在IE7中正确。如果我删除DOCTYPE标签,它也在IE8中看起来不错,但仍然无法在Google Chrome中正常显示。

我错过了什么?

谢谢 卡尔


1
一个超级建议:不要在html中使用style属性,而是将所有样式都包含在所谓的样式表中。使用:<link rel="stylesheet" href="css/style2.css" type="text/css" media="all" /> - Jonno_FTW
1
是的,我知道,但是为了这个例子,我认为这种方式会减少我在问题中插入的代码行数。 - Callprat
1个回答

3
为了控制浮动和位置,您需要记住两件事情:位置是相对于其父元素的绝对位置,并且通常需要尺寸,而浮动对象默认没有尺寸。
由于您的测试代表了一个简单的双列模型,请看一下这个很好的概述,它可能会让事情变得更加清晰:使用CSS实现等高列 因此,这里的技巧是给#text设置float和pos:rel,然后#right*Part就知道它们的位置在哪里了。
请看这里:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>

<style>
body             { margin: 0; }
#headers         { background: Olive; width: 300px; height: 50px; }
#text            { background: Navy; position: relative; width: 300px; display: block; float:left; }
#leftPart        { background: Gray; width: 200px; float: left;  display: inline-block; }
#rightPart       { background: Red; }

#rightTopPart    { background: Lime;     position: absolute; right: 0; top: 0; }
#rightBottomPart { background: Yellow;  position: absolute; right: 0; bottom: 0; }
</style>                                 

</head>
<body>
    <div id="headers"></div>
    <div id="text">
        <div id="leftPart">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
        <div id="rightPart">
                <div id="rightTopPart">top</div>
                <div id="rightBottomPart">bottom</div>
        </div>
    </div>
</body>
</html>

亲切问候,mtness

是的,你说得对。当我使用绝对定位时,我不需要浮动。谢谢! 卡尔 - Callprat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接