Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active October 6, 2015 10:36
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nathansmith/1e989f965bd7f655fc54 to your computer and use it in GitHub Desktop.
Save nathansmith/1e989f965bd7f655fc54 to your computer and use it in GitHub Desktop.
Examples of CSS selector strength.
* {}
tag {}
[attribute] {}
[attribute="value"] {}
.class {}
tag[attribute] {}
tag[attribute="value"] {}
tag.class[attribute] {]}
tag.class[attribute="value"] {}
#id {}
tag#id {}
tag#id[attribute] {}
tag#id[attribute="value"] {}
#id.class {}
tag#id.class {}
tag#id.class[attribute] {}
tag#id.class[attribute="value"] {}
/*
And of course, !important always
wins, no matter what the selector.
*/
tag {
key: value !important;
}
/*
And, the whole game begins anew, as soon as
there's a parent with a descendant selector.
*/
tag {}
body tag {}
tag#id.class[attribute="value"] {}
body tag#id.class[attribute="value"] {}
/*
Here's a cool trick you can do, since .foo can also
be written as attribute selector of [class="foo"].
*/
.foo[class~="foo"] {}
/*
Or, hey... Stacked attribute selectors!
*/
input[type="text"][disabled] {}
/*
Really, everthing except for tag/id
can be stacked, if multiples exist.
*/
.class-1.class-2[attribute-1="value"][attribute-2="value"] {}
tag#id.class-1.class-2[attribute-1="value"][attribute-2="value"] {}
@zachleat
Copy link

zachleat commented Apr 3, 2015

I think .foo[class="foo"] {} should read .foo[class~="foo"] {} to work if the element has multiple classes.

E[foo~="bar"] an E element whose "foo" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar"
via http://www.w3.org/TR/css3-selectors/

@nathansmith
Copy link
Author

True. I'll make that change. But also, didn't want to further confuse my designer coworker. 😄

@stowball
Copy link

stowball commented Apr 3, 2015

Don't forget about chaining the same class for extra specificity: .class1.class1 {}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment