9

Is there a way to have several selectors associated with a pseudo-class?

In other words, I want to make it so if an anchor, image, or button are hovered or focused on, they'll have a special border around them.

I tried this (shot in the dark):

(a,button,img):hover, (a,button,img):focus { border: 2px dashed black; } 

But Webstorm doesn't like it, and it doesn't activate.

I know that this works:

a:hover, a:focus { border: 2px dashed black; } 

But I'd like to be able to have it to apply to other selectors as well, without needing to repeat myself many times to apply it to all of them.

6
  • 1
    Maybe if you assign them all a common class (or) if you can use * (which I think is not quite what you want). Otherwise, pre-processors are your best bet. Commented Jan 13, 2016 at 16:34
  • 3
    Ugh, SO search sucks. Google isn't helping either. I've answered this same question (containing a very similar shot in the dark). Commented Jan 13, 2016 at 16:35
  • 1
    Fairly certain this is where pre-processors come into their own. You could make a modifier class that has the hover styles attached or you'd have to comma separate each element you want to attach the pseudo class to. Commented Jan 13, 2016 at 16:37
  • in order for CSS to be DRY, you are oing to need to use Preprocessors like SASS, LESS or Stylus Commented Jan 13, 2016 at 16:41
  • ... though technically that doesn't produce DRY CSS, it only lets you write DRY <whatever preprocessor flavor you use> Commented Jan 13, 2016 at 16:51

1 Answer 1

9

Your shot in the dark is actually very close to what's proposed for Selectors 4, except it takes the form of its own pseudo-class, :matches() (with the parentheses and the same comma-delimited syntax):

:matches(a, button, img):hover, :matches(a, button, img):focus { border: 2px dashed black; } 

which can be further simplified to:

:matches(a, button, img):matches(:hover, :focus) { border: 2px dashed black; } 

As it's not yet implemented outside of internal prefixes, you'll have to make do with writing it all out manually in the meantime:

a:hover, button:hover, img:hover, a:focus, button:focus, img:focus { border: 2px dashed black; } 

Or make use of a preprocessor to do all the heavy lifting for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Damn, thanks. I've been trying to avoid using preprocessors since this is just a toy site, and I really don't need them very much. Oh well, thanks.
It has now been renamed to: is() but works the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.