In CSS, a selector tells the web browser what HTML element or elements to apply a CSS rule to. In other words, a selector tells the web browser what HTML element or elements to format.
A class selector can be used to tell web browsers to apply a CSS rule to many HTML elements in a web page, even elements of different types and purposes.
A class selector is preceded by a period (.), followed by the class name. The period appearing before the class name in the CSS rule tells CSS that you are referencing a class selector.The class name is typically comprised of letters, numbers and hyphens only, since this provides the best compatibility with older web browsers. Class names cannot include spaces.
The CSS and XHTML example below are some examples of class selectors in action.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Web Development Tutorials.com</title>
<style type="text/css">
.red
{color: red;}
.blue
{color: blue;}
</style>
</head>
<body>
<p class="red">
The text in this paragraph will be red.
</p>
<p class="blue">
The text in this paragraph will be blue.
</p>
<h3 class="red">
The text in this heading will be red.
</h3>
</body>
</html>
The code above creates the 2 paragraphs and heading below.
The text in this paragraph will be red.
The text in this paragraph will be blue.
This another CSS and XHTML example of a class selector in action.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Web Development Tutorials.com</title>
<style type="text/css">
p.red
{color: red;}
</style>
</head>
<body>
<p>
The text in this paragraph will be red.
</p>
<p>
The text in this paragraph will also be red.
</p>
</body>
</html>
The code above creates the 2 paragraphs below.
The text in this paragraph will be red.
The text in this paragraph will also be red.
Use the text editor below to practice what you have learned.