/

HTML / CSS / JavaScript Tutorial

CSS Tutorial

2. Selectors

[this page | pdf | back links]

CSS is typically set out in the form of ‘rule-sets’, which involve a selector and a declaration block. Usually CSS is applied to types of elements. For example, the style rule

 

h3 {color: blue; text-align: center;}

 

has a selector which is h3 and a declaration block which is {color: blue; text-align: center;}. It tells the browser that any <h3> element (to which the rule applies) should be centre-aligned and appear in blue. As with HTML, line breaks and multiple spaces are ignored.

 

However, within HTML you can also define classes of elements with common formatting styles using the element’s class attribute. For example, the style rule

 

.center {color: red; text-align: center}

 

would indicate that any element with a class attribute equal to center should be centre-aligned and appear in red.

 

You can also apply CSS to elements of a specific type and class. For example, the style rule

 

h3.center {color: green;}

 

would indicate that <h3> elements that have their class attribute equal to center should be green.

 

In-file CSS can also be applied to individual elements, if the id attribute of the HTML element has been set (the id attribute should be unique within any given page). If you want to use this type of CSS then precede the id value by a hash (#) character.

 

For example, the style rule

 

#para1 {color: yellow}

 

would be applied to the HTML element with id equal to para1 (provided there is such an element) and it would appear yellow (unless overridden by a later style rule).

 

You can also group together rules for elements with the same style definitions, separating each selector with a comma. For example,

 

h1 {color: red;}

h2 {color: red;}

h3 {color: red;}

 

can be grouped together as follows to minimise code and make it easier to follow:

 

h1, h2, h3 {color: red;}

 

More general ways of identifying CSS selectors are set out here.

 


NAVIGATION LINKS
Contents | Prev | Next | CSS


Desktop view | Switch to Mobile