</>

CSS Selectors
and Specificity

CSS Selectors

Define the elements to which a set of CSS rules apply

Basic Selectors Syntax Definition Example
Universal selector * Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces * {
color: blue;
}
Type selector elementname Selects all elements that have the given node name section {
color: red;
}
Class selector .classname Selects all elements that have the given class attribute .index {
color: yellow;
}
ID selector #idname Selects an element based on the value of its id attribute. There should be only one element with a given ID in a document. #large-title {
color: green;
}
Attribute selector [attr] Selects all elements that have the given attribute [href] {
color: purple;
}

CSS Specificity

The order by which the browser decides which CSS style will be displayed

Specificity Definition Example
IDs Most specific selector in CSS h1 {color:red;} #headline {color: blue;} If the H1 tag had a ID of 'headline' the text would be blue
Chaining You can require an HTML element to have two or more CSS Selectors at the same time by combining multiple selectors h1.special {
color: red;
}
Selecting a tag and a class called 'special'
Descendant Combinator In addition to chaining selectors to select elements, CSS also supports selecting elements that are nested within other HTML elements. Also known as 'Descentdants' <ul class="main-list">
<li>Text</li>
</ul>
To select the nested <li> element = .main-list li{color: yellow}
Multiple Selectors To add more than one CSS style to selectors by adding a ',' h1, .menu {
color: green;
}
Separate with a comma
!important Rule Can be applied to a sepcific declaration, it will override any other style no matter how specific it is p {
color: red !important;
}
The <p> element will be purple