CSS Selectors

HTML5/CSS3: CSS Selectors

  • CSS
  • 3 mins read

In CSS, there are four types of selectors that you will use the most to specify CSS, and they are the element, id, class, and universal selector.

To start, below the body of HTML code that contains a section and a footer element. Here, the section element is assigned an id of "main", and the two <p> elements in this section have class attributes with the value "blue". Also, the <p> element in the footer has a class attribute with two values: "blue" and "right".

HTML Example

<section id="main">
    <h1>CSS Selectors Tutorial</h1>
    <p class="blue">First paragraph text.</p>
    <p class="blue">Second paragraph text.</p>
</section>
<footer>
    <p class="blue right">&copy; Copyright 2019</p>
</footer>

CSS Selectors Example

The following example shows the CSS rule sets that are used to format the HTML. Here the rule set in the first example uses the universal selector (*) so it applies to all HTML elements. This sets the top and bottom margins for all elements to .5em and the left and right margins to 1em.

* {margin: .5em 1em;}

Select Elements by Type

In the following example, it has two CSS rule sets to select elements by type. These are referred to as type selectors. To code a type selector, you just code the name of the elements.

h1 {
     font-family: Arial, sans-serif;
}

p {
     margin-left: 3em;
}

Select Element by ID

In the following example, it will select the element by its id. To do that, the selector is a hash sign (#) followed by an id value that uniquely identifies an element.

#main {
	border: 2px solid black;
	padding: 1em;
}

Select Elements by Class

The following CSS two rule sets select HTML elements by class. To do that, the selector is a period (.) followed by the class name.

.blue { color: blue;}
.right {text-align: right;}

Complete Example

<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        * {
            margin: .5em 1em;
        }
        
        h1 {
            font-family: Arial, sans-serif;
        }
        
        p {
            margin-left: 3em;
        }
        
        #main {
            border: 2px solid black;
            padding: 1em;
        }
        
        .blue {
            color: blue;
        }
        
        .right {
            text-align: right;
        }
    </style>
</head>

<body>
    <section id="main">
        <h1>CSS Selectors Tutorial</h1>
        <p class="blue">First paragraph text.</p>
        <p class="blue">Second paragraph text.</p>
    </section>
    <footer>
        <p class="blue right">&copy; Copyright 2019</p>
    </footer>
</body>

</html>

Output

CSS Selectors example output.See also: