Important Selectors which might not be the most popular selectors, but make your like 100 times easier:
Selector | Explanation | Example |
::after / ::before | prepends / appends a new element with the given content. | p::after { content: ‘This comes after’; } |
+ | for immediate adjacent sibling | p + p { } // 2 p’s next to each other |
~ | selects all sibling after of the given class within the same element | img ~ p { } // all p’s after img |
> | child element – for first descendent children only | ul > li { } //only li’s directly under ul |
::first-letter | selects the first letter of an element only | p::first-letter { font-size: 20px; } |
::first-line | selects first line of an element. (won’t work on display:inline) | p::first-line { color: red; } |
:first-child
:last-child :nth-child |
selects any first child of an element
selects any last child of an element selects the given child by position in an element |
p:first-child { color: red; }
p:last-child { color: green; } p:nth-child(2) { color: blue; } |
:first-of-type
:last-of-type :nth-of-type :nth-last-of-type |
selects first child of a specific type in an element
selects last child of a specific type in an element selects the given child by position of a specific type in an element selects the given child by position from bottom of a specific type in an element |
p:first-of-type { color: blue; } //1st of type p
p:last-of-type { color: navy; } //last of type p p:nth-of-type(2) { color: navy; } //2nd from top p:nth-last-of-type(2) { color: black; } //2nd from last |
:in-range /
:out-of-range |
for input type range, can be used as a validator | input:in-range { border: 1px solid green; }
input:out-of-range { border: 1px solid red;} |
:invalid | used for validations when using the required attribute to denote an error | input:invalid { border: 1px solid red; } |
:valid | used for validations when using the required attribute to denote valid | input:invalid { border: 1px solid green; } |
:matches | groups by selectors | :matches(nav, div) h1 { color: red; }
:matches(nav, div) :matches(h2,h3) { color: green; } |
:not(x) | selects all except given type or class | p:not(span) { font-size: 14px; } //span wouldn’t be 14px |
:only-child | if the type given is the only child in the element | div p:only-child { color: red; } //if p is the only child in div |
:required | indicated a required field when the required attribute is present | label:required { border: 1px solid red; } |
:target | matched the hash in the url and the id of the element | http://example.com/#games
<div id=”games”></div> #games { display: none;} #games:target { display: block;} |
* | universal selector refers to all elements and types | *{ margin: 0px; } |