Selectors are specifiers used to target different elements of the page and apply css styles to them
Types of Selectors
- Universal selector - selecting all elements
* {
//css declarations
}
- Type selector - opening tag name of an html element
type {
//css declarations
}
- Class selector - targeting the class attribute of an html element or group
.class_value {
//css declarations
}
- ID selector - targeting id attribute, meaning a single html element
#my-id {
//css declarations
}
-
Attribute selector
- By attribute type - targeting all elements with the attribute
[attribute] { //css declarations }
- By attribute value - targeting all elements with the attribute and specified attribute value
[attribute="value"] { //css declarations }
- By type, attribute and value - specifying the type of the element, the necessary attribute and it’s value
type[attribute="value"] { //css declarations }
-
Pseudo-class selector - can be attached to any other selector and targets a specific state (pseudo-class)
type:pseudo-class {
//css declarations
}
- Mixed selectors - requiring a selected element to match more than one selector
type.class {
//would target type elements with class
}
- Descendant selector - targeting an element out of children of another selected element(s)
.class type{
//would target type elements which are children of elements with class
}
Multiple Selectors
In order to add the same style to multiple selectors, separate the selectors with a comma over one declaration block:
type-selector,
.class-selector {
//css declarations
}
Selector Priority
The browser displays css styles based on their specificity. Id’s are the most specific and thus override other selectors used.
The specificity hierarchy:
- Inline styles
- Id selectors
- Classes, pseudo-class, Attributes
- Elements, pseudo-elements
In case of more complicated selectors the specificity is calculated based on three categories of weight corresponding to three types of selectors (id - class - type). For each selector belonging to a category increase the weight value by 1 in it’s column.
[type="password"] /* 0-1-0 */
input:focus /* 0-1-1 */
:root #myApp input:required /* 1-2-1 */
In case of two selectors targeting the same element, their specificity is compared based on columns left to right. If a selector has a bigger value in the id column, it wins the comparison regardless of the values in class and element columns.
Info
Inline Styles always have the highest specificity unless
!important
is used