How to Prevent Margin Collapse
In CSS, when margins of adjacent elements overlap, they can collapse, creating unexpected spacing issues. This behavior is designed to prevent overlap and maintain a consistent layout, but it can be challenging to disable when you need pixel-perfect control.
Standard Solutions
Typically, CSS tutorials suggest adding a border or padding to the elements to break the collapse. However, these solutions alter the visual appearance, which may not be ideal for layouts that rely on exact spacing and background images.
Invisible Spacer Div
To prevent margin collapse without affecting the layout, you can use an invisible spacer div with specific properties:
<div>
This div acts as a separator between the elements, effectively breaking the margin collapse.
Example Code
The following code demonstrates the use of an invisible spacer div:
<div>
In this example, the margins of the two divs will remain intact, ensuring the desired spacing without any visual side effects.
The above is the detailed content of How to Prevent CSS Margin Collapse Without Affecting Layout?. For more information, please follow other related articles on the PHP Chinese website!