CSS Margin Collapse
Sometimes the top and bottom margins of elements merge: instead of adding up, the two become a single margin, as big as the larger one. This is called margin collapse.
Note: Left and right margins never collapse; only top and bottom margins do.
Take an <h1> with a 50px bottom margin followed by an <h2> with a 20px top margin. You might expect 70px between them, but margin collapse leaves 50px, the larger value.
Headings
A 20px top margin meets a 50px bottom margin, and the gap that results is 50px.
Prompt
An HTML page that shows margin collapse between two headings.
In an internal
<style> block, give the <h1> a margin-bottom of 50px and the <h2> a margin-top of 20px. Add an h1 followed by an h2. The gap between them collapses to 50px, not 70px.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
h1 {
margin-bottom: 50px;
}
h2 {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>The gap between the headings collapses to 50px, the larger of the two margins.</p>
</body>
</html>
Paragraphs
With 30px top and bottom margins on each paragraph, you get a 30px gap between them rather than 60px, thanks to the collapse.
Prompt
An HTML page that shows margin collapse between two paragraphs.
In an internal
<style> block, give each <p> a margin-top of 30px and a margin-bottom of 30px. Add two paragraphs. The gap between them collapses to 30px, not 60px.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
margin-top: 30px;
margin-bottom: 30px;
}
</style>
</head>
<body>
<p>First paragraph.</p>
<p>Second paragraph. The gap between the two paragraphs collapses to 30px, not 60px.</p>
</body>
</html>
All CSS Margin Properties
The margin properties at a glance:
margin— one declaration for all the margins.margin-bottom— the bottom margin.margin-left— the left margin.margin-right— the right margin.margin-top— the top margin.