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:

<html>
    <head>
        <title>Classes</title>
        <link rel="stylesheet" href="theme.css" type="text/css"/>
    </head>

    <body>
        <h1 class="headings">My heading</h1>
        <p class="blue">My paragraph</p>

        <h1 class="headings">My second heading</h1>
        <p class="large blue">My second paragraph</p>
        <p class="large">My third paragraph</p>

    </body>
</html>

And here is the CSS code (theme.css file):

.headings{
    font-family: Arial;
    color: green;
}

.blue{
    color: blue;
}

.large{
    font-size: 20pt;
}

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