Outer margin merging or collapse of css

Posted by tskweb on Mon, 28 Oct 2019 15:06:04 +0100

The first situation:

It is known that two div s with width and height of 100px and margin of 20px are arranged vertically, as shown in the following figure:

 

When setting the margin bottom: 40px of css1 or the margin top: 40px of css2, the phenomenon is as follows:

 

Conclusion:

Only when the vertical outer margins of two vertically arranged boxes are close together will there be a merging problem. This problem does not need to be solved. It is ok to remember that whoever has a larger outer margin will use the outer margin.

There is no merging problem with horizontally arranged boxes.

The following experiments confirm that:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
       div{
           /*Extract the code with common characteristics of two boxes*/
            width:100px;
            height: 100px;
            margin: 20px;
            float: left;   /*Floating left to achieve horizontal box arrangement*/
        }
        /*Set different colors for two boxes*/
        .div1{
            background: pink;
        }
        .div2{
            background:#CCC;
        }
    </style>
</head>
<body>

    <div class="div1">css1</div>
    <div class="div2">css2</div>

</body>
</html>

Phenomenon:

The second situation:

A div1 with width and height of 200px embeds a div2 with width and height of 100px. When setting margin: 30px for div2, the phenomenon is as follows:

At this time, the margin of the big div outside becomes 30px. Here's how to solve this problem:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
      
        .div1{
            width: 200px;
            height: 200px;
            background: pink;
            overflow: hidden;     /*Code to solve the problem*/
       /*border:1px solid black The second solution: set a border for the big div*/
} .div2{ width:100px; height:100px; margin: 30px; background:#CCC; } </style> </head> <body> <div class="div1"> <div class="div2">css</div> </div> </body> </html>

 

You need to write overflow: hidden in a large div. this code can be understood as letting the browser check whether there is a problem when displaying the div. if there is a problem, the browser will solve it. The second solution is shown in the code above.

The final phenomenon is:

 


For more professional front-end knowledge, please go to [ape 2048] www.mk2048.com

Topics: IE