In the example below, h1 is the selector, everything else is the declaration. Colour and font-size are properties and red and 22px are the values. This rule-set would result in any h1 elements being displayed at 22px and coloured red. Individual declarations are separated by semicolons, and the declaration block is surrounded by curly braces.
Example of a CSS Rule-set:
In CSS, Selectors are used to denote which HTML element you want to style. There are several different CSS Selectors available to use.
These select HTML elements based on their proper HTML name. Some examples are
<li>, etc. The previous image shows an example of an element selector (h1).
You can assign a specific id to an element. An id selector, written using the hash (#) character, is then used to apply the style only to elements given that id. For example:
You can then apply the id to an element like this
<body id="body1">Anything inside these tags will be aligned right, at 14px and bold
The class selector selects any HTML element which has the specific class attribute, written using the period (.) character. For example:
You can then apply the class to an element like this
<p class="bold">Anything inside these tags will be bold and 12px
You can also use a class selector to specify only specific HTML elements are styled by the class. For example:
Only <p> elements with the bold class will be styled as above. A
<h1> element given the bold class would not be styled.
You can apply multiple classes to elements. If you had classes called p.bold and p.red, you could apply the styling of both like:
<p class="bold red"></p>.
Pseudo-class selectors allow you to assign styles to an element only when it is in certain states. Some examples of pseudo-class selectors include:
These pseudo-classes allow you to style a link differently depending on whether it is unclicked, hovered over, has been visited, etc.
Another example of a pseudo-class selector is :first-child. When this is applied to another element, such as <p>, it will apply the style only to the first <p> that is a child of another element. For example:
The Universal Selector
The universal selector selects every HTML element on the page, overruling any other selector on the page that include the same properties. The universal selector is written using the asterisk (*) character, for example:
Grouped Selectors / Selector Lists
If you have several elements with the same style definitions, you can group them into one selector to minimize code. For example:
These selectors could instead be grouped and written as: