Problems caused by position being out of document flow

We know that using position:absolute and position:fixed will cause the element to fall out of the document flow, which will cause corresponding problems. An example is as follows:

<!DOCTYPE html>
<html>
<head>
    <title>position</title>
    <style>
        .div1{
            background-color: red;
            padding:20px;
        }
        .div2{
            width: 200px;
            height: 200px;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class="div1">
        <div class="div2"></div>
    </div>
</body>
</html>

Examples are as follows

That is, the child element supports the parent element.

But once the position of the child element is fixed or absolute, it will be out of the document flow, and the consequence of this is that the parent element cannot be stretched, as shown below:

<!DOCTYPE html>
<html>
<head>
    <title>position</title>
    <style>
        .div1{
            background-color: red;
            padding:20px;
            position: relative;
        }
        .div2{
            position: absolute; // 添加position:absolute使其脱离文档流
            width: 200px;
            height: 200px;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class="div1">
        <div class="div2"></div>
    </div>
</body>
</html>

Solution 1: Set the height of the parent element equal to the height of the child element in js.

Solution 2: Force the height of the parent element. (For similar problems caused by width, the width is forcibly set)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691680&siteId=291194637