CSS margin collapse explained

Coder Coder · Beginner ·🌐 Frontend Engineering ·4mo ago

Key Takeaways

This video explains the concept of CSS margin collapse, its causes, and how to prevent it from happening in web development.

Full Transcript

Hey folks, in this video we're going to talk about some quirks that you might see when working with margins. Specifically, something called margin collapse that can make margins behave in ways that you might not expect. So, let's start quickly with what margins do. Margins allow you to add space around an element that kind of pushes away other neighboring elements. For example, you can use margins to create space between an element and its parent. So here on this demo website that we have open, we have a gray parent div and inside it has a purple child div nested inside it as you can see in the markup. Now there is a little space between them already because I added 20 pixels of padding to the parent. But let's say I want to add more space and on the child I will add a margin of 40 pixels. So now when we save there's even more space around the child. And in our dev tools if I hover over the child you can see that there is that margin adding space between the child and the parent. You can also use margins to add space between sibling elements meaning elements that are next to each other in the HTML. So on this demo we have two elements and they both have a dark green background color and they're next to each other. So if I add a margin of 20 pixels, this will be applied to both. And we save. Now we can see that both of these elements have a 20 pixel margin around them, which is adding space around them and to the parent as well as between the two sibling elements. You can also set margins to a negative number. This negative margin will pull the element closer to other elements around it instead of pushing them farther away. So here we have two elements. We have the first element which is purple and it has a margin bottom of 20 pixels which is what's adding the space between them. Then we have a turquoise element underneath it. And let's add a negative margin to it. So I'm going to set margin top to 80 pixels. And then when I save, the turquoise element has been pulled up 80 pixels from where it was before and it's now overlapping the purple element. However, one weird quirk with margins is that when you have two vertical margins that directly face each other, they are going to cause something called margin collapse. So in our demo website here, I'm going to create an H1 tag and give it some text. And then below that, I'm going to create a paragraph. And let's add some Lauram Ipsum placeholder text to that. So now we have both of them on our website. So both the H1 and the paragraph tags do have margins on top and bottom already from the default browser styles. And I can see it if I inspect let's say the headline, we can see it has top and bottom margin here. And the paragraph also has a top and bottom margin. However, if you look closer, let me just zoom in a little bit. You might notice that the paragraph's top margin and the headlines bottom margin are both basically occupying the same space between these two elements. Instead of stacking the two margins one after the other, as you might expect, the two margins have instead collapsed into one another until the headline's bottom margin hits the top of that paragraph's content box. So, this is a classic example of margin collapse. And this was originally a feature back when most websites were very HTML and textbased to avoid having a double margin between subsequent blocks of text. Now, another quirk of margin collapse is that the margins of an element can collapse outside of its parent element. So, let's make a parent element for the paragraph. I'm going to create a div with a class of block and I'm going to put the paragraph inside this div. There we go. Then in our styles, let's add a style rule for the block class. And I'll set the background color to light blue so we can see it better. So now on our website, the spacing before the paragraph is still the same. And if we inspect the paragraph, you can see that the paragraph's margins are actually extending outside of this block div, its parent, which has that light blue color. So you can see the margins are going outside of it. And in this case, this is a good thing because we do still want space between the headline tag and the paragraph. However, margins collapsing outside the parent can sometimes not be what you want. So, let me show you one example of that. So, on our website, let's say that we want to have the blue background block be around the H1 tag as well as the paragraph. So, I'm going to take the H1 tag and move it inside the block div. There we go. And I want the blue block to be right at the very top of the website. So, I'm also going to add a style on the body tag and remove the default margin that it has from the browser styles. So, now when we save, we don't want any space around the block. It should be up at the very top, but as you can see, there is white space above the headline. So if we inspect the H1 tag, we can see that the top margin is also extending outside of the block div like the paragraph was before it. And it is basically pushing the entire block down from the top of the web page, which is not really what we want. So if you have margin collapse happening like here, and you don't want it to happen, well, how can you get rid of it? Fortunately, there are some CSS style rules that you can add to an element to prevent the margins from collapsing outside of it. So, in this case, we want to prevent margin collapse outside of the block div. So, in our block class styles, we can one way we can prevent it is by adding padding to this div. So if I add padding of 10 pixels and I save and now the blue block is completely flush against the top side of the website. And you can actually do the same thing with border. Border will do the same thing as padding and remove margin collapse. So let's try border uh 2 pixel solid. Oops. Magenta. If we save, you can see again the blue background is going all the way to the top and we have that border. However, you might not want to, you know, have to add padding or border if you don't really need it just to prevent margin collapse. Even though you could do a hack like adding a transparent border, so that way you can't see it, but it is still preventing margin collapse. But there's actually another style rule that you can add that will prevent margin collapse and it's not going to have any side effects like adding padding or border to your styles. So let's comment out our border style and add the style which is setting display to flow root. So when we save now the top margin is not extending outside of the block anymore. In adding display flow route, it creates something called a block formatting context. And this is honestly just a very confusing way of saying that it's going to force things like collapsing margins and also the old CSS floats that its children might have back within its bounds. So display flow route is a solution to margin collapse. But personally, as an alternative, I try to avoid using margin to add space between a child and its parent like we've basically done here with the H1 tag. So, in my opinion, the better way to add space between the H1 tag and the block div would be to add the space just with padding on the block itself in the parent. So in our styles for the H1 tag, let's remove the margin, the margin top. And then in the block, we can add padding again of let's say 20 pixels to add 20 pixels of space all around the content in it. So now we have added space before the H1 tag inside the block parent. And since we're using padding to add the space, we don't need to worry about margin collapse happening. All right, so that was a quick video on how margin collapse works and how you can avoid it happening. So next up, we're going to talk about the CSS display property.

Original Description

What causes margin collapse in CSS, and how to prevent it from happening. 💥 Get 20% off 1-yr of Frontend Mentor Pro with my code JESSCHAN20 -- https://www.frontendmentor.io/?via=jesschan Source code: https://github.com/thecodercoder/css-layout/tree/main/02-margin-collapse CSS Layouts playlist: https://www.youtube.com/playlist?list=PLUWqFDiirlst8pCZ1R1exwnFSKXEigGIL ____________ 💻 LEARN TO CODE 💻 MY COURSE: 🟢 Responsive Design for Beginners -- Learn how to build a website from scratch -- https://coder-coder.com/responsive RECOMMENDED RESOURCES: Tools and resources I use myself and highly recommend, with exclusive discounts (affiliate links help support this channel-- thank you!) 🔷 Frontend Mentor Pro -- Practice building real-world projects (10% off with code JESSCHAN10) -- https://www.frontendmentor.io/?via=jesschan 🔷 Boot.dev -- Learn back-end development (25% off) -- https://www.boot.dev/?promo=CODERCODER 🔷 Zero to Mastery -- Learn web dev, AI, DevOps and more with 100+ courses -- https://academy.zerotomastery.io/a/aff_s3xc407h/external?affcode=441520_ti97uk6b OTHER STUFF: 🟢 Coder Coder Dark -- My VS Code theme -- https://marketplace.visualstudio.com/items?itemName=CoderCoder.codercoder-dark-theme 🟢 Coder Coder Merch -- get my hoodie, coffee cup, and more! -- https://coder-coder.com/merch SOCIALS: https://twitter.com/thecodercoder https://www.instagram.com/thecodercoder #css #javascript #html
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Coder Coder · Coder Coder · 0 of 60

← Previous Next →
1 How to Make a Super Simple HTML Website [Tutorial]
How to Make a Super Simple HTML Website [Tutorial]
Coder Coder
2 How to make an animated sticky header with CSS and JavaScript!
How to make an animated sticky header with CSS and JavaScript!
Coder Coder
3 How to get coding help by researching online
How to get coding help by researching online
Coder Coder
4 IG Live - Advice for beginner web developers
IG Live - Advice for beginner web developers
Coder Coder
5 Quick Start Guide to Parcel JS
Quick Start Guide to Parcel JS
Coder Coder
6 Build a responsive website with HTML & CSS - Part 1 [Live Coding]
Build a responsive website with HTML & CSS - Part 1 [Live Coding]
Coder Coder
7 Build a custom Linktree page for Instagram with HTML & CSS
Build a custom Linktree page for Instagram with HTML & CSS
Coder Coder
8 Gulp 4 Crash Course for Beginners
Gulp 4 Crash Course for Beginners
Coder Coder
9 How to use CSS position to layout a website
How to use CSS position to layout a website
Coder Coder
10 CSS: 4 Reasons Your Z-Index Isn't Working
CSS: 4 Reasons Your Z-Index Isn't Working
Coder Coder
11 Coding a landing page website with HTML & CSS
Coding a landing page website with HTML & CSS
Coder Coder
12 Learn web development as an absolute beginner
Learn web development as an absolute beginner
Coder Coder
13 How to write media queries in CSS
How to write media queries in CSS
Coder Coder
14 How to build a 2-column layout using flexbox | HTML/CSS
How to build a 2-column layout using flexbox | HTML/CSS
Coder Coder
15 How to build a simple responsive layout with CSS grid
How to build a simple responsive layout with CSS grid
Coder Coder
16 Write code faster in VS Code with Emmet shortcuts
Write code faster in VS Code with Emmet shortcuts
Coder Coder
17 How I setup VS Code for a beginners front-end workflow
How I setup VS Code for a beginners front-end workflow
Coder Coder
18 How to make a background-image transparent in CSS
How to make a background-image transparent in CSS
Coder Coder
19 Build a responsive website from scratch with HTML & CSS | Part 1: Navigation bar
Build a responsive website from scratch with HTML & CSS | Part 1: Navigation bar
Coder Coder
20 Animated Hamburger Menu in CSS/JS | Build a responsive website from scratch (Part 2)
Animated Hamburger Menu in CSS/JS | Build a responsive website from scratch (Part 2)
Coder Coder
21 Animated mobile menu with CSS/JS | Build a responsive website from scratch (Part 3)
Animated mobile menu with CSS/JS | Build a responsive website from scratch (Part 3)
Coder Coder
22 How to stay motivated when learning to code?
How to stay motivated when learning to code?
Coder Coder
23 Responsive hero | Build a responsive website from scratch (Part 4)
Responsive hero | Build a responsive website from scratch (Part 4)
Coder Coder
24 Responsive 4-column layout with flexbox | Build a responsive website from scratch (Part 5)
Responsive 4-column layout with flexbox | Build a responsive website from scratch (Part 5)
Coder Coder
25 Responsive 4-column layout with CSS Grid | Build a responsive website from scratch (Part 6)
Responsive 4-column layout with CSS Grid | Build a responsive website from scratch (Part 6)
Coder Coder
26 Building a footer using CSS Grid | Build a responsive website from scratch (Part 7)
Building a footer using CSS Grid | Build a responsive website from scratch (Part 7)
Coder Coder
27 Browsersync + Sass + Gulp in 15 minutes
Browsersync + Sass + Gulp in 15 minutes
Coder Coder
28 Responsive card UI with flexbox and hover effects | HTML/CSS
Responsive card UI with flexbox and hover effects | HTML/CSS
Coder Coder
29 CSS grid cards with animated hover effect | HTML/CSS
CSS grid cards with animated hover effect | HTML/CSS
Coder Coder
30 How I learned to code and landed a job (no CS degree!)
How I learned to code and landed a job (no CS degree!)
Coder Coder
31 Building the website for my course (coding timelapse)
Building the website for my course (coding timelapse)
Coder Coder
32 How to debug your code faster 🔥
How to debug your code faster 🔥
Coder Coder
33 Full timelapse + walkthrough of building my website
Full timelapse + walkthrough of building my website
Coder Coder
34 Your questions answered!! ✨100K Q&A✨
Your questions answered!! ✨100K Q&A✨
Coder Coder
35 Building a pricing block with HTML & PuRe CSS
Building a pricing block with HTML & PuRe CSS
Coder Coder
36 Use the Google Maps API to build a custom map with markers
Use the Google Maps API to build a custom map with markers
Coder Coder
37 Building an accordion with HTML, CSS & JS (Part 1)
Building an accordion with HTML, CSS & JS (Part 1)
Coder Coder
38 How to make your own VS Code theme!
How to make your own VS Code theme!
Coder Coder
39 How to build an accordion with HTML, CSS, and JavaScript (Part 2)
How to build an accordion with HTML, CSS, and JavaScript (Part 2)
Coder Coder
40 Life/channel update
Life/channel update
Coder Coder
41 Building a Light/Dark Dashboard, Part 1
Building a Light/Dark Dashboard, Part 1
Coder Coder
42 What is NPM, and why do we need it? | Tutorial for beginners
What is NPM, and why do we need it? | Tutorial for beginners
Coder Coder
43 Building a Node.js app (as a JavaScript noob) |  🔴 LIVE CODING
Building a Node.js app (as a JavaScript noob) | 🔴 LIVE CODING
Coder Coder
44 Free website project ideas for your portfolio #shorts
Free website project ideas for your portfolio #shorts
Coder Coder
45 How to add quickly emojis on Windows #shorts
How to add quickly emojis on Windows #shorts
Coder Coder
46 Building a Light/Dark Dashboard, Part 2
Building a Light/Dark Dashboard, Part 2
Coder Coder
47 Learn to code with these 4 free resources! #shorts
Learn to code with these 4 free resources! #shorts
Coder Coder
48 Learn flexbox with these 4 resources! #shorts
Learn flexbox with these 4 resources! #shorts
Coder Coder
49 [Typing sound] Comparing mechanical vs regular keyboard
[Typing sound] Comparing mechanical vs regular keyboard
Coder Coder
50 Building a Light/Dark Dashboard, Part 3
Building a Light/Dark Dashboard, Part 3
Coder Coder
51 what making web development tutorials is really like 😅 #shorts
what making web development tutorials is really like 😅 #shorts
Coder Coder
52 Generate website starter files with just one command!
Generate website starter files with just one command!
Coder Coder
53 emojis in code
emojis in code
Coder Coder
54 Stay motivated when coding: don't compare yourself with others #shorts
Stay motivated when coding: don't compare yourself with others #shorts
Coder Coder
55 Building a Light/Dark Dashboard, Part 4
Building a Light/Dark Dashboard, Part 4
Coder Coder
56 Coding motivation: slow and steady wins the race 🐢🏁
Coding motivation: slow and steady wins the race 🐢🏁
Coder Coder
57 Sass @import is being replaced with @use and @forward
Sass @import is being replaced with @use and @forward
Coder Coder
58 Coding motivation tip: keep your goal in mind
Coding motivation tip: keep your goal in mind
Coder Coder
59 How do websites work?
How do websites work?
Coder Coder
60 Building a Light/Dark Dashboard, Part 5
Building a Light/Dark Dashboard, Part 5
Coder Coder

Related AI Lessons

Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Prepare for a frontend developer interview with Capgemini by reviewing JavaScript fundamentals and practicing common interview questions
Medium · JavaScript
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with 10 essential tools for modern web app development
Medium · Programming
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with top 10 developer tools in 2026
Medium · JavaScript
The US Frontend Engineer Market in 2026: A Data-Driven Reality Check (and the Bias That Stops Us Seeing It)
US frontend engineer hiring demand peaked in 2022 and remains flat-depressed in 2026, contrary to common assumptions
Dev.to AI
Up next
How to Open KIT Files (CodeKit Project)
File Extension Geeks
Watch →