Title!
Paragraph
I have a div
(parent) that contains another div
(child). Parent is the first element in body
with no
Found an alternative at Child elements with margins within DIVs You can also add:
.parent { overflow: auto; }
or:
.parent { overflow: hidden; }
This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:
.parent {
padding-top: 1px;
margin-top: -1px;
}
Update by popular request: The whole point of collapsing margins is handling textual content. For example:
h1, h2, p, ul {
margin-top: 1em;
margin-bottom: 1em;
}
Title!
Title!
Paragraph
Title!
Paragraph
- list item
Because the browser collapses margins, the text would appear as you'd expect, and the Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new block formatting context in CSS speak. The and
won't add up, but slide into each other (they collapse). The same happens for the
and
element.
overflow
or margin trick will give you that.