Oliver Scholz Oliver Scholz - 1 year ago 56
CSS Question

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


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;

<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 class="a">fifth</p>
<p class="a">sixth</p>

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download