了解 CSS 位置属性

问题描述 投票:0回答:1

我创建了以下简单的 HTML 来帮助我理解位置属性,我有一个关于下面的 HTML 在浏览器 (Chrome) 中显示方式的简单问题:

<!DOCTYPE html>
<html>
<head>
    <style>
    .fixdiv {
        position: fixed;
        height: 100px;
        width: 150px;
        top: 0;
        left: 100px;
        background-color: lightblue;
        }
    .absdiv {
        position: absolute;
        height: 100px;
        width: 200px;
        top: 50px;
        left: 200px;
        background-color: red;
        }
    .reldiv {
        position: relative;
        height: 100px;
        width: 150px;
        top: 20px;
        left: 100px;
        background-color: lightgreen;
        }
    </style>
</head>
<body>
    <div>
        <p>text with normal flow is this text here.
        text with normal flow is this text here.</p>
        <p>text with normal flow is this text here.
        text with normal flow is this text here.</p>
        <p>text with normal flow is this text here.
        text with normal flow is this text here.</p>
    </div>
    <div class="fixdiv">
        <p>This is a div with fixed position</p>
    </div>
    <div class="absdiv">
        <p>This is a div with absolute position</p>
    </div>
    <div class="reldiv">
        <p>This is a div with relative position</p>
    </div>
</body>
</html>

这很好,但我有一个问题,为什么在浏览器中查看时,在固定框和绝对框之前插入了一些空格,而不是相对框?请参阅屏幕截图。

html css css-position
1个回答
0
投票

那是段落边距。在固定或绝对容器中,您会看到框内的边距。在相对容器中,边距是段落原始位置计算的一部分,但它不随元素移动。

您只需在段落上设置

margin: 0
即可消除多余的空间。

© www.soinside.com 2019 - 2024. All rights reserved.