Class selector
You can apply styles to all elements with the specified class by using the class selector.
A class selector is a name preceded by a period (.).
.example { color: red; }
In the above example, the style is applied to all elements that have the class "example".
p.example { color: red; }
The class can also be used with a particular element type. In the above example, the style is applied to only P elements that have the class "example".
Note : A class name cannot start with a number.
Bad example : .1example { }
Good example : .example1 { }
Element
You can specify a class for elements by using the class attribute.
<p class="example">Example text</p>
Two or more classes can also be specified for an element. (They are separated by a space.)
<p class="example1 example2">Example text</p>
The class with a particular element type
<html>
<head>
<title>TAG index</title>
<style type="text/css">
p.example { color: red; }
</style>
</head>
<body>
<h1 class="example">The style is not applied to this heading</h1>
<p class="example">The style is applied to this text.</p>
<h2 class="example">The style is not applied to this heading</h2>
<p class="example">The style is applied to this text.</p>
</body>
</html>
Only the class name
<html>
<head>
<title>TAG index</title>
<style type="text/css">
.example { color: red; }
</style>
</head>
<body>
<h1 class="example">The style is applied to this heading</h1>
<p class="example">The style is applied to this text.</p>
<h2>The style is not applied to this heading</h2>
<p>The style is not applied to this text.</p>
</body>
</html>
Multiple classes
<html>
<head>
<title>TAG index</title>
<style type="text/css">
.example1 { color: red; }
.example2 { text-decoration: underline; }
</style>
</head>
<body>
<p class="example1">Only the color style.</p>
<p class="example2">Only the decoration style.</p>
<p class="example1 example2">The color and decoration styles.</p>
</body>
</html>
Nesting
The style can be applied only to elements within a certain element by using descendant selectors.
.example p { color: red; }
In the above example, the style is applied to all P elements within the element with the class "example". (Other P elements are unaffected)
<html>
<head>
<title>TAG index</title>
<style type="text/css">
.example p { color: red; }
</style>
</head>
<body>
<div class="example">
<p>The style is applied to this text.</p>
<p>The style is applied to this text.</p>
</div>
<p>The style is not applied to this text.</p>
</body>
</html>