26

In the below example, I want to create a CSS rule that applies only to the header with the text "Blockhead".

 <div class="gumby">
     <span class="pokey"></span>
     <h3>Blockhead</h3>
     <h3>Clay rules</h3>
 </div>

Can I use parentheses, such as (.gumby > .pokey) + h3? If not, what is my alternative?

Starwarswii
  • 1,335
  • 12
  • 13
smartcaveman
  • 38,142
  • 26
  • 119
  • 203

2 Answers2

27

No, parentheses are not valid operators in CSS selectors. They are reserved for functional notations, such as :lang(), :not(), and :nth-child().

You don't need them anyway; .gumby > .pokey + h3 by itself will work just fine.

This is because a sequence of selectors and combinators is always read linearly. Combinators don't have any sort of precedence. The selector can be interpreted as

Select an h3 element
that immediately follows an element with class pokey
that is a child of an element with class gumby.

And because of how node trees work, the use of sibling and child combinators here implies that both .pokey and the h3 are children of .gumby, which in your case they are, because of its statement that both of them are siblings.

Community
  • 1
  • 1
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
  • 6
    While "You don't need them anyway" is true, parentheses would help to avoid repetition, if they were allowed, like: `.gumby > (.hokey, .pokey) + h3` – user686249 Sep 10 '15 at 10:21
  • 4
    @user686249: That role will be filled by the `:matches()` pseudo so there's no need for a brand new syntactic construct. – BoltClock Sep 10 '15 at 12:20
  • Awesome, didn't know that one. – user686249 Sep 10 '15 at 17:30
  • @BoltClock This comment is the actual answer. – John Mar 17 '16 at 22:07
  • 3
    @John: Not to this question. This question says nothing about grouping selectors, and the comment I was responding to was left by a completely different individual. You're probably thinking of something like http://stackoverflow.com/questions/34771974/associating-multiple-selectors-with-a-pseudo-class, to which `:matches()` *is* the actual answer. (You *could* argue that it can be used for something like `:matches(.gumby > .pokey) + h3`, but that's completely redundant anyway since it has the exact same meaning as `.gumby > .pokey + h3`.) – BoltClock Mar 18 '16 at 04:05
  • 1
    :matches() was renamed to :is() in 2018 (Chrome & Firefox but not Edge). https://github.com/w3c/csswg-drafts/issues/3258, https://developer.mozilla.org/en-US/docs/Web/CSS/:is – Denis Howe Mar 06 '21 at 20:50
0

h3 is not inside .pokey so you must ommit .pokey from the rule

All u'd be able to do is

.gumby h3 {}

or do this

 <div class="gumby pokey">
     <h3>Blockhead</h3>
     <h3>Clay rules</h3>
 </div>

.gumby.pokey h3 {}

if a tag has more than one class you can pile them up in css if you don't use a space character

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Jase
  • 589
  • 3
  • 9