Don't mix up your code with container and content elements. This way you won't be able to do it like you're willing to, like APAD1 said.
Instead, use container elements and for each content element a new child node. That way, you can access single child elements with the first-child
selector.
This works for me:
<div id="highlight">
<div id="first">First Text</div>
<div id="second">Second Text</div>
<div id="third">Third Text</div>
</div>
CSS:
div#highlight div:first-child{margin:10px;color:red}
Working example here: http://jsfiddle.net/B5Ej9/
Update: TL;DR: It isn't possible to do so with the given HTML without any ugly hack!
If there is no chance to change the HTML, you will need some kind of hack to workaround, as (like Quentin) answered, all the child objects automatically inherit width
and margin
from parent objects in DOM. The following example might work for some indentation on the left margin of the div
, but I know: It's an ugly workaround that should just clarify what I mean (and why you might consider getting the HTML to be changed). Here you go, with your original HTML:
<div id="first">
First Text
<div id="second">Second Text</div>
<span id="third">Third Text</span>
</div>
And the workaround CSS:
div#first { margin: 20px; color: red; background: grey;}
div#first *:not(:root) { margin-left: -20px; color: blue}
That way, you will add a margin to the first
div and inherit it to all the childs (second
and third
), but everything that is not inside the root will be set to a negative margin on the left. But have a look at the background (http://jsfiddle.net/vag58/), you will notice that the background of all child elements is still inherited and you're never ever gonna change that.