Class Selector

Selectors are used to select elements in a  web page that you want to style. There are many types of CSS selectors including:

  • Element selector – element selectors select all of the elements in a web page with the specified element name (eg. p, h1, h2).
  • Class selector – class selectors apply a style to all of the elements that use that class. Eg. a style of green text with a yellow background could be applied to multiple paragraphs that use that class name.
  • ID selector – ID selectors are unique for each element and are used when you want to apply a style to just one element on a web page.
  • and many more.

If you have completed the previous tutorials, then you have already used element selectors. In this tutorial we will focus on using the class selector. A class selector can be used when you want to apply a style to all of the elements that use that class name.

When we uses classes, we specify the class name in the element tag. In the example below, a paragraph is using the ‘blue’ class:

<p class = "blue">This text is blue</p>

Then, in the CSS code you need to define the class by placing a period/full stop before the class name. A period means that this will be a class:

.blue{
       color:blue;
}

Watch the video below to see how you can use classes in your web pages. Then scroll down to view the sample code.

Here is the sample HTML code:

<!DOCTYPE html>
<html>
<head>
 <title>Classes</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet5.css" type="text/css"/>
</head>
 
<body>
 <p class="red">This paragraph will be red</p>
 <p class="green">This paragraph will be green</p>
 <p class="blue">This paragraph will be blue</p>
</body>
 
</html>

And here is the sample CSS code (in a seperate style sheet called stylesheet5.css in the resources directory:

.red{
 color:red;
}
 
.green{
 color:green;
}
 
.blue{
 color:blue;
}

In the next tutorial, we will take a look at the ID selector.