JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 5: Types of CSS Selectors


In previous lessons, you have learned that the basic structure of a CSS  comprises selectors and their attributes. Besides that, you have also learned how to use various types of selectors to create styles for webpages. In this lesson, we shall examine the selectors in more details. We shall also introduce some new selectors which we have not learned before.

5.1 Universal Selector

A universal selector matches all elements on a webpage. Usually the asterisk symbol * is used to denote a universal selector.

For Example,

*{ font-family: verdana;}

The typeface verdana will be applied to the text of the whole document

5.2 Type Selector

A type selector matches every element type that appears in the document.

For example,

 p  { color:blue; font-family:arial;}

The CSS rules applied to all <p> elements that appear in the document where the text enclosed between <p> and </p> tags will be displayed in blue color and in arial font.

Here is another example,

 h1,h2,h3{ font-weight: bold;}

Since the elements are sharing the same declarations, they can also be written as

h1{ font-weight: bold;} h2{ font-weight: bold;} h3{ font-weight: bold;}

The CSS rule applied to <h1>, <h2> and <h3> elements. All text enclosed between <h1></h1>, <h2></h2> and <h3></h3> tags will be displayed as bold text.

5.3 ID Selector

An ID selector is used to uniquely identify an element in a document. A CSS ID selector contains a "#"  followed by the ID value, which is an identifier. It matches an HTML element with an ID attribute that has a value that matches the one specified by CSS ID selector.

For example,


#section1 { font-size:14px}

The text include the following tag will have font size 14 pixels.

<p id="section1"></p>

5.4 Class Selector

The class selector is similar to the ID attribute because is it also used to specify an element that matches the value of the class attribute. We create a class attribute using a period or dot like the following example. Example

<style>

.intro{color:blue; font-family: verdana;font-size: 120%}

HTML

<p class="intro">All the text enclosed between the p tags will be in blue, having typeface verdana and font size 120% bigger than the default font</p>
</style>

The Output is as shown below:

All the text enclosed between the p tags will be in blue, having typeface verdana and font size 120% bigger than the default font


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy