Margin-top push outer div down
To prevent the inner div
's margin-top
from pushing down the outer div
, apply overflow: hidden
to the parent div
:
Diving Deep
Understanding Margin Collapse
The margin-top behavior can be confusing. When applied to an inner element, its parent is also pushed down due to a CSS concept called "margin collapse".
Using Padding Instead of Margin
Consider padding instead of margin-top for spacing your h1
inside its parent div
. It avoids affecting the location of the parent:
Going Inline
Note that changing the h1
's display property to inline-block can prevent it from affecting the outer div
:
Overflow Control: Getting Un-Visible
By changing the overflow
property of the parent div
to anything other than "visible", we can effectively control the margins of internal components:
Playing with Positioning
Applying relative positioning offers a neat alternative:
Flexbox Galore
The usage of Flexbox also allows for more elegant solutions:
Making Pseudo-Elements Work for You
Creating a pseudo-element using :before
can mimic the margin's effect:
Margin Behaviors and Their Exceptions
Not all elements succumb to the convoluted semiotics of "margin collapse":
- Behold the unwavering Floats.
- The Absolutely Positioned minions.
- The change-minded Overflow.
- The Inline-blockers.
Hence, by strategizing the use of these properties, one can rule out unruly margins.
Root Element Characteristics
Bear in mind that the root element's margin does not collapse with the margins of its descendants, granting you more control over your page's overall design.
Pseudo-elements: Styling without Extra Markup
The use of pseudo-elements makes your HTML cleaner and easier to read, as they don't require additional markup and allow for semantic structure preservation.
Was this article helpful?