Selectors
To apply a style to an element on a web page, the element needs to be referenced.
Elements are referenced using selectors – you ‘select’ which element or elements you want to style.
When the page loads, your CSS will tell the HTML what style to apply to each element.
Key Points
Selectors are required to assign CSS rules to elements.
Basic selectors can be used to assign CSS rules to elements.
IDs can be used to assign rules to a single element.
Classes can be used to assign rules to groups of elements.
Basic Element Selectors
Element Selectors are the most basic selectors used within HTML and CSS.
To reference an element, we simply use the elements tag that we use to display it in HTML.
| Tag | Purpose |
|---|---|
| h1, h2, h3, h4, h5, h6 | To style a heading |
| p | To style a paragraph |
| ul / ol | To style a list |
| li | To style an item on a list |
| img | To style an image |
| div | To style a div |
| a | To style a hyperlink |
Styling an element using a seletor
To style the element, a rule must be created using the html tag of the element as the selector.
Between curly brackets, rules are then set by using properties and values.
In the below example, all h1s are set to size 22 font and the colour red.
- Font size is the property, 22px is the value.
- Colour is the property, red is the value.
h1{
font-size: 22px;
color: red;
}
IDs and Classes
IDs and Classes allow developers to add styles to groups of different elements or single unique elements.