CSS Selectors

Element Selector

The element selector selects all elements with the specified element name.

Example, select and style all <p> elements:

p {

background-color: yellow;

}

CSS Syntax

element {

css declarations;

}

Class Selector

The .class selector selects elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the name of the class.

You can also specify that only specific HTML elements should be affected by a class.

To do this, start with the element name, then write the period (.) character, followed by the name of the class (look at Example 1 below).

HTML elements can also refer to more than one class (look at Example 2 below).

CSS Syntax

.class {

css declarations;

}

The id Selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element should be unique within a page, so the id selector is used to select one unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

The style rule below will be applied to the HTML element with id="para1":

Example:

#para1 {

text-align: center;

color: red;

}

Descendant Selector

The descendant selector matches all elements that are descendants of a specified element.

The following example selects all <p> elements inside the <div> element.

Example:

div p {

background-color: yellow;

}

Universal Selector

The universal selector, written "*", matches the name of any element type. It matches any single element in the document tree.

If the universal selector is not the only component of a simple selector, the "*" may be omitted. For example:

Pseudo Selector

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

Syntax

The syntax of pseudo-classes:

selector:pseudo-class {

property:value;

}

Grouping

When several selectors share the same declarations, they may be grouped into a comma-separated list.

In this example, we condense three rules with identical declarations into one. Thus,

h1 { font-family: sans-serif }

h2 { font-family: sans-serif }

h3 { font-family: sans-serif }

is equivalent to:

h1, h2, h3 { font-family: sans-serif }

Order of Specificity

  1. Inline styles - An inline style is attached directly to the element to be styled. Example: <h1 style="color: #ffffff;">.
  2. IDs
  3. Classes, attributes and pseudo-classes
  4. Elements and pseudo-elements
Go Back