将相对元素放入绝对元素时会发生什么?

时间:2014-05-04 19:58:50

标签: html css

绝对:完全忽略流程。 相对:在正常流量的上下文中,但也可以移动。

按预期在红框内显示绿框。

<html>
<head>
    <title>Lets see what occurs</title>
    <style>
        #box_1 {
            position: absolute;
            top: 100px;
            left: 100px;
            right: 0px;
            bottom: 0px;
            background:red;
        }

        #box_2 {
            position: absolute;
            top: 100px;
            bottom: 100px;
            left: 40px;
            right: 0px;
            background:green;
            }

    </style>
</head>
<body>
<div id="box_1"><div id="box_2"></div></div>

</body>
</html>

为什么不能这样做?

<html>
<head>
    <title>Lets see what occurs</title>
    <style>
        #box_1 {
            position: absolute;
            top: 100px;
            left: 100px;
            right: 0px;
            bottom: 0px;
            background:red;
        }

        #box_2 {
            position: relative;
            top: 100px;
            bottom: 100px;
            left: 40px;
            right: 0px;
            background:green;
            }

    </style>
</head>
<body>
<div id="box_1"><div id="box_2"></div></div>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

相对位置: 即使移动相对定位元素的内容,元素的保留空间仍保留在正常流程中。

绝对位置: 通过绝对定位,元素可以放置在页面的任何位置。下面的标题距离页面左侧100px,距离页面顶部150px。

答案 1 :(得分:1)

absolute定位被引用到具有absoluterelative定位的父/祖先。 relative定位被引用到自己,即它在页面流中的假定位置。因此,当您将absolute div置于另一个absolute div内时,左/上/等等。引用是关于父母的边界;当您将孩子div定位为relative时,会在其应有的位置参考自己的边界。

在这里,您可以阅读一篇关于它的好文章:http://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

答案 2 :(得分:0)

问题不是在绝对定位的div中使用相对定位,而是为每个边(顶部,右边,底部和左边)设置值,并且元素没有定义的宽度。当您为每个边设置值时,它将尝试将元素定位到每个将产生意外结果的值。

以下内容:

#box_1 {
    position: absolute;
    top: 100px;
    bottom: 0;
    left: 50px;
    right: 0;
}

应该更像是:

#box_1 {
    position: absolute;
    top: 100px;
    left: 50px;
}

当我移除两个不必要的位置值并添加宽度/高度时,看看这个小提琴看到定位是否按预期工作:http://jsfiddle.net/S4fvs/9/

有时您想要占用整个窗口,因此设置top: 0right: 0bottom: 0left: 0会导致块级元素填充所有可用空间。这对于在普通内容之上创建新上下文非常有用,例如对于可能变长的模式而言,滚动而不滚动页面背后的页面。