如何强制一个元素与position:absolute来调整父div的大小?

时间:2022-07-18 20:30:28

Easy question. I just want to understand the logic. Why elements with position:absolute (and float:left too) do not "take up space" like position:relative? And how to force an element with position:absolute to resize the parent div?

简单的问题。我只想了解逻辑。为什么带位置的元素:绝对(和浮动:左)也不像位置那样“占用空间”:相对?以及如何强制一个元素与position:absolute来调整父div的大小?

View DEMO

I need to understand this condition to solve some problems.

我需要了解这个条件来解决一些问题。

<style>
    .relative,
    .absolute {
        height: auto;
        width: 200px;
        border: 1px solid black;
        margin: 10px;
    }

.relative svg {
        position: relative;
}

.absolute svg {
        position: absolute;
}
</style>


<!-- The height:auto works! -->
<div class="relative">
    <svg width="50" height="50">
        <rect width="50" height="50" style="fill:rgb(255,0,0)" />
    </svg>
</div>

<!-- The height:auto don't works -->
<div class="absolute">
    <svg width="50" height="50">
        <rect width="50" height="50" style="fill:rgb(0,0,255)" />
    </svg>
</div>

1 个解决方案

#1


position: absolute breaks normal flow...

位置:绝对打破正常流量......

The normal flow of the document is how your elements stack one on top of each other, from the top down, in the order in which they appear in your markup.

文档的正常流程是您的元素从上到下按照它们在标记中出现的顺序堆叠在一起的方式。

Unlike the static and relative values, an absolutely positioned element is removed from the normal flow. This means you can put it anywhere, and it won’t affect or be affected by any other element in the flow.

与静态和相对值不同,绝对定位的元素将从正常流中移除。这意味着您可以将它放在任何位置,它不会影响流程中的任何其他元素或受其影响。

Source: http://alistapart.com/article/css-positioning-101

CSS SPEC: http://www.w3.org/TR/CSS21/visuren.html

CSS SPEC:http://www.w3.org/TR/CSS21/visuren.html

#1


position: absolute breaks normal flow...

位置:绝对打破正常流量......

The normal flow of the document is how your elements stack one on top of each other, from the top down, in the order in which they appear in your markup.

文档的正常流程是您的元素从上到下按照它们在标记中出现的顺序堆叠在一起的方式。

Unlike the static and relative values, an absolutely positioned element is removed from the normal flow. This means you can put it anywhere, and it won’t affect or be affected by any other element in the flow.

与静态和相对值不同,绝对定位的元素将从正常流中移除。这意味着您可以将它放在任何位置,它不会影响流程中的任何其他元素或受其影响。

Source: http://alistapart.com/article/css-positioning-101

CSS SPEC: http://www.w3.org/TR/CSS21/visuren.html

CSS SPEC:http://www.w3.org/TR/CSS21/visuren.html