Question

is there any way to select a CSS-element that is the first child of its parent, counting text nodes? I want to remove the top margin of a heading if it is at the top of its parent, but if I use:

#content h1 {
    margin-top: 1em;
}
#content h1:first-child {
    margin-top: 0;
}

and have some HTML like

<div id="content">
    This is some text.
    <h1>A heading</h1>
    Some more text.
</div>

the margin is still removed. Is there any way in CSS to prevent this?

No correct solution

OTHER TIPS

Remove the margin, not just the margin-top, h1 element is pushing the next element down

#content h1 {
    margin-top: 1em;
}
#content h1:first-child {
    margin: 0px;
}

Demo Fiddle

If you want to remove all except first

#content h1:not(:first-child) {
    margin: 0px;
}

Updated Fiddle

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 floated 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.”)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top