Submodule 1.1: Selectors

  • id 
  • Class and multiple classes 
  • specific context (ul li)
  • Group the selectors 

Class selector

class is another type of selector. In contrast with id, class is not unique. This means that the same class can be used multiple times in an HTML page.

The class selector is created by a period . followed by the selector’s name. The class selector selects elements with a specific class attribute (name).

Thus in our CSS the class will be:

.mypadding {padding-top: 5px;}

 And in the HTML we will have: 

<p class=”mypadding”> This paragraph will have 5px padding from top </p>

Moreover, an element can have multiple classes.

Example:

<p class=”mypadding myborder mycenter myfontsize”> This paragraph has reference to four classes </p>
 When we use class selectors?

Class selectors are used when we want to apply the same style to multiple elements on our page but not to every element of the same type.

Imagine that you have a page with 100 <p> and 5 <ul> lists.

Assume that you want to apply the same style to 50 of these <p> tags and 1 <ul> list. In this case, class is the appropriate selector.

If you wanted to apply the same style to all <p> tags, then the appropriate selector would be the element selector.

 Example

The CSS rules:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
        .fontBlue {color:blue}
        .fontRed {color:red}
        .baclLime {background:lime}
        .backGrey {background:lightgrey}
    </style>
  </head>
  <body>
    <p class="fontBlue baclLime">My first paragraph</p>
    <p class="fontBlue backGrey">My second paragraph</p>
    <p class="fontRed baclLime">My third paragraph</p>
<p class="fontRed backGrey">My fourth paragraph</p>
  </body>
</html>


will create a page displayed as:

 multiple classes

Exercise

  1. Open your editor, create a new file and save it as exersice01.1.02.html in the folder "advanced".
  2. Copy the above code and paste it in the new file.
  3. Modify and save the file. The browser's output should be as shown in the following image:

multiple classes

Solution: