Home > Web Front-end > CSS Tutorial > How to Prevent Margin Collapsing Between a Child Div with `margin-top` and a Parent Div Without a Top Border?

How to Prevent Margin Collapsing Between a Child Div with `margin-top` and a Parent Div Without a Top Border?

Mary-Kate Olsen
Release: 2024-11-27 06:07:13
Original
443 people have browsed it

How to Prevent Margin Collapsing Between a Child Div with `margin-top` and a Parent Div Without a Top Border?

CSS: Managing Margin-top when Parent Div Lacks Top Border

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template