Overriding Margin Collapsing in CSS
Margin collapsing is a CSS feature that merges adjacent margins into a single, larger margin. This can be problematic for layouts that rely on pixel-perfect margins.
Avoiding Collapsing with Extra Elements
CSS tutorials commonly suggest adding borders or padding to break collapsing. However, these solutions introduce unwanted visual effects.
Invisible Spacer Fix
To avoid these side effects, consider using an invisible spacer element. This element can be achieved with:
<div>
This spacer prevents margin collapsing by creating a zero-sized discontinuity between the elements.
Example
The following HTML code demonstrates how to use the spacer:
<div>
This code will render three elements with 100px margins, without collapsing the margins between them.
The above is the detailed content of How Can I Prevent CSS Margin Collapsing Without Affecting Layout Appearance?. For more information, please follow other related articles on the PHP Chinese website!