Check Demo
CSS Margin Collapsing
float:left;
or display: inline-block
solves the above issue
Let’s explore exactly what the consequences of collapsing margins are, and how they will affect elements on the page.
The W3C specification defines collapsing margins as follows:
“
In this specification, the expression collapsing margins means that
adjoining margins (no non-empty content, padding, or border areas, or
clearance separate them) of two or more boxes (which may be next to
one another or nested) combine to form a single margin.
”
In simple terms, this definition indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero.1 In the case where one element has a negative margin, the margin values are added together to determine the final value. If both are negative, the greater negative value is used. This definition applies to adjacent elements and nested elements.
There are other situations where elements do not have their margins collapsed:
- floated elements
- absolutely positioned elements
- inline-block elements
- elements with overflow set to anything other than visible (They do
not collapse margins with their children.)
- cleared elements (They do not collapse their top margins with their
parent block’s bottom margin.) the root element
This is a difficult concept to grasp, so let’s dive into some examples.