Oliver Scholz Oliver Scholz - 4 months ago 9
CSS Question

CSS: why doesn't the right element get selected?

http://codepen.io/oscholz/pen/qNYPVL

I am trying to select only the Random unattached paragraph.

I've tried a number of things that I think should all work (see below or the



p:first-of-type {
color: red;
}
.a:not(.relevant) {
color: red;
}
.a:nth-child(1) {
color: red;
}
.a:first-child {
color: red;
}

<h1>Hi</h1>
<h2 class="important">Hi again</h2>
<p class="a">Random unattached paragraph</p>
<div class="relevant">
<p class="a">first</p>
<p class="a">second</p>
<p>third</p>
<p>fourth</p>
<p class="a">fifth</p>
<p class="a">sixth</p>
<p>seventh</p>
</div>





None of them do. What am I missing?
I know I could change the HTML, but I don't want to do that. :)

Answer

There are many ways. You need to decide the semantic meaning of what you want to select and devise your selector based on that.

  • body > p.a would select all p.a elements that are direct children of the body tag (i.e., not nested inside any containers).
  • .important + p.a would select any p.a elements that come immediately after an .important element.
  • p.a:nth-of-type(1) would select the first paragraph tag if it has class a.
  • p.a would select all p.a elements, and you could then use .relevant p.a to override (or undo) any attributes on the ones you didn't want to affect.

Well-written semantic HTML should always describe the purpose of an element based on context, tag choice, and class and/or id attributes. If your document's markup is not semantic, there is only so much you can do to create a generalized CSS selector for the components you want to affect.