Date : Feb 2018
Element
Used to apply style on all the elements targeted by their tag name :
div { } /*targets all <div> elements*/
span { } /*targets all <span> elements*/
input { } /*targets all <input> elements*/
Class
.
is a class selector. It targets every element with a specific class attribute :
.my-class { } /*targets every element with the "my-class" class*/
div.my-class { } /*targets every div with "my-class" class*/
Id
#
is the id selector. It targets every element with a specific id attribute :
#my-id { } /*targets every element with the "my-id" id*/
(note that an id should be unique and applied to only one element but the css will be applied anyway on every element with the same id attribute ! )
Attributes
You can target an element by any of its attributes and attributes value :
[alt] { } /*targets every element with an alt attribute */
input[type="checkbox"] { } /*targets every <input> element with the "type" attribute value set to "checkbox"*/
You can also use regex in your attribute selector :
a[href*="www"] { } /*targets every <a> element with a "href" attribute value containing "www"*/
a[href^="https://"] { } /*targets every <a> element with a "href" attribute value beginning with "https://"*/
a[href$=".com"] { } /*targets every <a> element with a "href" attribute value ending with ".com"*/
a[href~="example"] { } /*targets every <a> element where "href" attribute value is a space-separated list containing the word "example"*/
a[href|="example"] { } /*targets every <a> element where "href" attribute value is a dash-separated list beginning with the word "example"*/
Pseudo-class
A pseudo-class selector is a selector preceded by :
or ::
.
Some are used to apply style on a specific state of an element.
button:hover { } /*the style will apply on a button when the user's mouse hovers it*/
button:disabled { } /*the style will apply on every button with "disabled" attribute*/
a:visited { } /*targets the <a> elements the user has visited*/
Others are used to target specific elements by their position in the DOM.
div p:last-child { } /*targets the last <p> in a <div> element*/
div p:first-child { } /*targets the first <p> in a <div> element*/
div p:nth-child(even) { } /*targets all the even <p> elements in a <div> (even, odd, 1n, 2n, 2n+1, ...)
:not()
pseudo-class can be used to avoid applying style on specific elements.
It takes every selector type as argument.
div:not(.my-class) { } /* targets every <div> that doesn't have the "my-class" class attribute.*/
div p:not(:last-child) { } /*targets all <p> elements in my <div> except the last one*/
input:not([type="checkbox"]) { } /*targets all <input> elements that are not checkboxes type*/