Home > Web Front-end > CSS Tutorial > How Does Margin Collapsing Work in CSS?

How Does Margin Collapsing Work in CSS?

Susan Sarandon
Release: 2024-12-16 10:00:28
Original
685 people have browsed it

How Does Margin Collapsing Work in CSS?

Margin Collapsing: An Explanation

In CSS, margin collapsing is a behavior that affects the spacing of adjacent elements on a web page.

Understanding Margin Collapsing

Contrary to popular belief, margin collapsing does not occur when you have no margins, padding, or borders set on an element. Instead, it occurs when two adjacent vertical margins are present. In such cases, the larger of the two margins is applied, while the smaller one is ignored.

Examples of Margin Collapsing

Consider the following example:

<div>Block A</div>
<div>Block B</div>
Copy after login

Assume Block A has a bottom margin of 3em and Block B has a top margin of 2em. Without any other styling applied, the vertical spacing between the blocks would be 3em because the bottom margin of Block A is the larger of the two.

Preventing Margin Collapsing

You can prevent margin collapsing by adding borders or padding to the adjacent elements. This creates a gap between the elements, even if the margins are set to 0.

For example, adding a 1px top border to Block B would result in a vertical spacing of 5em between the blocks.

Conclusion

Margin collapsing is a fundamental aspect of CSS styling that affects the spacing of elements on a web page. It's important to understand the conditions under which margin collapsing occurs to create intended layouts and avoid unexpected results.

The above is the detailed content of How Does Margin Collapsing Work in CSS?. 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