smartcaveman
smartcaveman

Reputation: 42246

Are parentheses allowed in CSS selectors?

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?

Upvotes: 38

Views: 20974

Answers (3)

cmarangu
cmarangu

Reputation: 234

As of 2022, we can now use the :is() selector for this purpose:

https://developer.mozilla.org/en-US/docs/Web/CSS/:is

:is(.gumby > .pokey) + h3 {
  color: blue;
}
<div class="gumby">
     <span class="pokey"></span>
     <h3>Blockhead</h3>
     <h3>Clay rules</h3>
 </div>

If I understand correctly, :is() can simulate both logical AND :is(A):is(B):is(C) and logical OR :is(A, B, C), allowing for powerful combinations. Don't forget to use it in concert with other structural pseudo-classes such as :not() and :nth-child(), CSS Combinators, and DOM Traversal methods such as document.querySelectorAll(). Also, the :where() pseudo-class is identical except that it has 0 specificity, while :is() takes the specificity of its most specific argument.

Upvotes: 4

BoltClock
BoltClock

Reputation: 723618

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.

Upvotes: 39

Jase
Jase

Reputation: 599

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

Upvotes: 0

Related Questions