The overlap between the margins of CSS parent elements and the margins of subset elements

One reason:
1. Between sibling blocks, the upper and lower margins of the margin attribute often overlap. The larger value shall prevail instead of addition.
2. Between the parent and child blocks, the upper and lower margins of the child will overlap with the upper and lower margins of the parent, and the larger value shall prevail instead of addition.

Two solutions:
1. Use floating or absolute positioning for parent or child elements (floating or absolute positioning does not participate in the folding of margin)
2. Parent overflow: hidden;
3. Parent setting padding (breaking non-blank folding conditions)
4. Parent set border (destroy non-blank folding conditions)

Before
Insert picture description here
clearing the float: After clearing the float:Insert picture description here

Code:

<!DOCTYPE html><html lang="en">
<head>    
<meta charset="UTF-8">    
<meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title>   
 <style>
 /* 解决嵌套的父子元素margin共享办法 */                
 /* 设置padding-top: 1px; */    
 /*设置 border: 1px solid blueviolet; */           
 /* 给父级设置overflow: hidden; */
 /*设置浮动解决盒子共享 float: left; */ 
 /* 设置绝对定位position: absolute; */            
 .a {
     
                      
     width: 200px;           
     height: 100px;          
     background-color: #096;                  ;        
    }              
  .b {
     
                         
     width: 200px;            
     height: 50px;           
     background-color: red;           
      margin-top: 20px;        
      }    
  </style>
</head>
<body>    
      <div class="a">  </div>            
      <div class="b">   </div>
 </body>
 </html!


Guess you like

Origin blog.csdn.net/GengFuGuo/article/details/108481874