Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CSS to target any element that has ANY two classes on it?

Our production environment is using an adaptation technology that is incompatible with multiple css classes. This means it's easy to forget and use two classes when styling HTML, and have it break once it gets to production.

I would like to use CSS as a way to highlight when someone forgets and accidentally applies two classes to an element.

Something like this is my intent, although of course this is invalid. It should highlight any element that has two classes applied to it:

.*.* { /* not valid (I wish) */
  outline:2px dotted red;
  }

I understand that this would work if I knew the classes, the problem is I want to flag ANY two classes:

.classA.classB { /* not good enough */
  outline:2px dotted red;
  }

I understand I could do this with JS and a bookmarklet, and maybe that is the only solution. If it is possible with just CSS that would be better as it would automatically flag things for all developers and QA.

like image 343
SimplGy Avatar asked Jul 27 '11 16:07

SimplGy


3 Answers

I just found an acceptable answer:

[class*=" "] {
  outline:2px dotted red;
  }

This highlights anything with a space in the class attribute. It gets some false positives, because sometimes spaces in a class attribute happen legitimately as a result of legible server side code, but I prefer the false positives to false negatives.

Any better ideas?

like image 101
SimplGy Avatar answered Oct 17 '22 18:10

SimplGy


To remove most false positives (e.g. space-padded attribute values), you can use this selector:

[class*=" "]:not([class^=" "]):not([class$=" "]) {
    outline: 2px dotted red;
}

This still does not filter out repeated classes in values such as class="foo foo" as pointed out by Phrogz in your own answer, but it's better than nothing, and I think that's much less likely to occur than class attributes with whitespace padding.

like image 32
BoltClock Avatar answered Oct 17 '22 16:10

BoltClock


This is not possible using CSS alone.

And, if I may say so, your production environment is silly. CSS without multiple classes is like a tag cloud with only one tag allowed per item. It defeats some of the purpose. Fix your production environment to not abuse CSS in this manner, instead of limiting your authors from properly, semantically describing the content.

like image 1
Phrogz Avatar answered Oct 17 '22 18:10

Phrogz