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.

TagPurpose
h1, h2, h3, h4, h5, h6To style a heading
pTo style a paragraph
ul / olTo style a list
liTo style an item on a list
imgTo style an image
divTo style a div
aTo 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.

More about IDsMore about Classes

National 5 Requirements

You should be able to apply styles to HTML elements.

You should be able to identify the properties and values of a CSS rule.