In the example given in the OP, you could (remove the :first-child
rule and) add
#content {
margin-top: 1em;
}
This would collapse (combine and overlap) with the h1
’s margin if there’s no text before the heading, but if there is the h1
would have a separate top margin. You’d then just have to adjust the bottom padding/margin of whatever is preceding so that your #content
is positioned desirably, or perhaps alternatively add a ::before
pseudo-element with a negative margin (which will collapse with and cancel out the container’s margin) to do the trick:
#content:before {
display: block;
margin-top: -1rem;
content: ' ';
}
Note that if h1
has a different font-size
then 1em
will different so you would have to account for that or use a fixed unit such as rem
or px
.
(This doesn’t help in my case – I want to add a top-margin to a float
ed img
if there’s some text before it in the containing <p>
[in WordPress-generated content]. But margins of float
-ed elements don’t collapse with their container, and the general answer to the question is “no, there’s no such selector.”)