Selectors, Classes and IDs

The selector is the part of an CSS commands that identifies the parts of a page to be formatted.

Simple Selectors

HTML tags can be specified:

h1 {
    font-family: 'Trebuchet MS', sans-serif;
    color: orange;
}

id Selectors

An HTML element can be given an id – any id can only be used once on a page:

<p id="pageAuthor">Mr Thoresen</p>

CSS can then format that specific id:

#pageAuthor {
    text-align: right;
    color: grey;
}

Class Selectors

An HTML id can only be used once on page.
A class can be be used several times on the same page.

<p class="caption">Photograph by Mr Thoresen</p>
...
<p class="caption">Photograph by Ms Bailey</p>

CSS can then format all occurrences of that class:

.caption {
    text-align: center;
    color: grey;
}

Grouping Selectors

If two or more elements will have the same formatting, the common elements can be grouped.

In this example, both h1 and h2 elements wll use the Trebuchet font, but only h1 elements will have orange text:

h1, h2 {
    font-family: 'Trebuchet MS', sans-serif;
}
h1 {
    color: orange;
}

Universal Selector

The universal selector will apply styles to every page element.

Example: Browsers use default settings for margins and padding when displaying HTML elements. To override these defaults, a universal selector (*) can be used at the top of a stylesheet to set the margin and padding of every element to 0. This will allow students to witness only the margins and paddings they actually code.

 
* {
    padding: 0px;
    margin: 0px;
}

Descendant Selectors (a Combinator)

Descendant selectors give a list of two or more selectors, separated with spaces. The formatting rules are only applied to those selectors that are inside the previous selectors.

Example: This block will format only format list items that are inside an unsorted list that are inside a navigation block.

nav ul li {
    float:left;
    width:80px;
    text-align:center;
}

This is used on the page for horizontal navigation bars.