AIgo Notes
Home
Tools
Record Audio
Upload Audio
Upload PDF
YouTube Link
Upload Text
Upload Image
Pricing
Download
Unlimited notes
Login
Home
›
Public Notes
›
Note details
Why adding a margin on a child element affects the parent
BY a4gqz
August 25, 2025
•
Public
Private
8259 views
Understanding Margin Collapse in CSS
Introduction
Encountering unexpected white space due to margin changes.
Both hero and top nav sections have a purple background, but white space persists.
What is Margin Collapse?
Definition
: Margin collapse occurs when the top and/or bottom margins of elements merge into one another.
Example
: A headline with a 40-pixel bottom margin and a paragraph with a 20-pixel top margin results in a total margin of 40 pixels, not 60.
Margin Collapse Behavior
Initially intended to prevent double margins and excessive space between text elements.
If a first child in a parent has a top margin, it may push outside the parent's bounds.
Preventing Margin Collapse
Solution
: Create a block formatting context on the parent of the affected element.
Block Formatting Context
: Concept relating to how elements and parent elements interact on a webpage.
Methods to Create a New Block Formatting Context
Display Flow Root
: The most direct modern approach.
Alternative Methods
:
Add Border
: A transparent border can prevent margin collapse.
Add Padding
: Set padding to 1 pixel as a workaround.
Use Flex/Grid
: Setting display to grid or flex affects block formatting context.
Preferred Approach
Use
display: flow-root
for resolving margin collapse without hacky alternatives.
Best Practices for Specific Situations
Using Padding Over Margin
: To add space inside a parent element instead of relying solely on margin.
Avoid Margin Collapse Confusion
: Prefer padding for creating space within a parent element’s borders.
Conclusion
CSS can be challenging due to quirks like margin collapse.
Use the correct techniques to navigate these issues effectively.
Additional Resources
Video creation detailing other CSS issues like margin collapse.
Upcoming course titled "Responsive Design for Beginners."
Comments & Feedback
Invitation for viewers to share their margin collapse experiences or CSS quirks.
Course link available in the description for more learning.
Thanks for watching!
Transcript
Share & Export
Why adding a margin on a child element affects the parent