This article shares the problem of margin collapse and methods to solve margin collapse. It has certain reference value and I hope it will be helpful to everyone's study.
Margin is to set the outer margin of the element. Normally when setting the margin value, the parent element should be positioned relative to the browser, and the child element is positioned relative to the parent element. However, we often encounter situations where no matter how the value is set for margin There is no response. Today I will share with you the method to solve this problem.
html code
<div class="box1"> <div class="box2"></div> </div>
css code
.box1{ width:200px; height:200px; background-color:rgb(16,128,214); } .box2{ width:100px; height:100px; background-color:rgb(128,227,248); }
Rendering
##When setting the margin-top value ChangeWhen setting margin-top:100px for box1, box2 also sets margin-top:100px. Only the parent element is 100px downward relative to the browser, but the position of the child element relative to the parent element is not. Change But when the margin-top set for the child element: 150px is greater than the height of the parent box, the child element will no longer be positioned relative to the parent element but with Move the parent element down 150px relative to the browser positioning From the above content we can know what margin collapse ismargin collapse
Margin collapse occurs when the parent is positioned relative to the browser but the child is not positioned relative to the parent. The child seems to have collapsed relative to the parentThe vertical margin of the parent-child nested elements. The parent-child elements are combined together. The two of them will take the largest valueto solve the problem. The method of margin collapse
The essence is to trigger the box's bfc (block format context block-level formatting context) to change the rendering rules of the parent elementMethod 1
position:absolute;Set relative positioning Solve the margin collapse problem by adding a relative positioning attribute to the parent elementMethod 2
display:inline-block;Set to line block level elementMethod 3
float:left and float:right; Use float to change the style
Method 4
overflow:hiddenPartially hidden display of the overflow box Summary: the above That’s it for this article. I hope to be helpful.The above is the detailed content of How to solve the problem of margin collapse. For more information, please follow other related articles on the PHP Chinese website!