解释CSS中绝对定位的行为。

3
我想知道CSS中这种行为是否正常,以及为什么会这样? 我的问题是关于position: absolute; 我有两个div,第一个包含图像,当使用0 bottom和right 0的绝对位置定位时,它会粘在页面的末尾(但不是真实页面的末尾,而是显示视图的页面末尾) 请注意,它没有任何具有绝对或固定或相对位置的父元素

JSbin演示

结果中的图像 这是完整的代码

<!DOCTYPE html>
<html>
<head>
    <title></title>

    <style>
        body {
            background: #808080;
            /*height:1200px;*/
        }

        .content {
            background: rgba(0, 148, 255, 0.69);
            /*min-height:400px;*/
            width: 900px;
            margin: 0 auto;
            border: 6px groove #00ff90;
        }


        h1 {
            position: relative;
            top: 5px;
            right: 5px;
        }

        p {
            /*position: relative;*/
            /*top: 150px;*/
            /*right: 5px;*/
        }


        img {
            border: 3px groove #0ff;
            width: 400px;
            position: absolute;
            /*top:0px;
    right:0px;*/
            bottom: 0px;
            right: 0px;
        }
    </style>
</head>
<body>
    <div class="content">
        <h1>why we should using reletive posittios</h1>
        <p>
            Es un hecho establecido hace demasiado tiempo que un lector se distraerá con el contenido del texto de un sitio mientras que mira su diseño. El punto de usar Lorem Ipsum es que tiene una distribución más o menos normal de las letras, al contrario de usar textos como por ejemplo "Contenido aquí, contenido aquí". 
        </p>
        <p>you can move any element and did't brak the stucture , it has many advantages and disadvantages too !!</p>
        <img src="pet.jpg" alt="Alternate Text" />
    </div>


    <div>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>
        <h1>test</h1>

    </div>

</body>
</html>

如果由于语言障碍无法正确解释我的问题,我希望代码片段能够解释清楚。

1个回答

5

这是正常的行为,因为您在任何父级中都没有position:relative,所以CSS使用视口高度作为参考。

如果您添加body { position:relative},它将相对于页面底部。

如果您添加.content { position:relative},它将位于蓝色内容框的底部。


1
是的,感谢您的声明。这是我与CSS相关的“顿悟时刻”之一,因为我想象中它们应该直接与页面交互而不是视口,所以这种行为会自动发生。 - user4833581
1
没错,position:relative 对我来说也是一个“恍然大悟”的时刻。我和你一样 - CSS 有很多违反直觉的东西。 - Miro

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