When a child element has a margin-top and its parent element lacks a top border, the child element's margin can create visual inconsistencies. As illustrated in the provided image, the orange div appears to push the green div down, although the latter does not have a top border.
To resolve this issue without adding a border to the parent div, you can implement a solution that prevents margin collapsing. Margin collapsing is a CSS behavior that occurs when margins of adjacent elements (in this case, the green and orange divs) collapse into a single margin.
To prevent margin collapsing, add the following CSS to the parent element:
overflow: auto;
Applying overflow:auto to .body in the provided CSS snippet will prevent margin-collapsing and maintain the desired visual arrangement. You can find more details about margin collapsing in the W3C specification: http://www.w3.org/TR/CSS2/box.html#collapsing-margins
The above is the detailed content of How to Prevent Margin Collapsing Between a Child Div with `margin-top` and a Parent Div Without a Top Border?. For more information, please follow other related articles on the PHP Chinese website!