Skip to content

06. Class Selectors

martin@mustbebuilt.co.uk edited this page Sep 3, 2024 · 1 revision

With class selectors, it is up to you to give the selector a name. This should be unique and should begin with a dot .. An example of a class selector based rule is as follows:

.maintext {
       font-size: 12px;
       color: #000;
}

In the above example, a class of name maintext is declared.

To apply the class selector use the class attribute that can be added to any HTML element that you want to assume the style. For example the following applies the rule .maintext to the first and third paragraphs but not the second paragraph.

<p class="maintext">Paragraph One</p>
<p>Paragraph Two </p>
<p class="maintext">Paragraph Three</p>

This gives you more flexibility in page design, as the class attribute can be added to any tag.

We can use a class selector to replace our inline selector from earlier.

Find the inline selector:

<span style="color:#ff0000;">dynamic web pages</span>

and replace it with:

<span class="highlight"> dynamic web pages</span>

Then inside <style> create a CSS rule for the class named highlight ie:

.highlight{
    color:#FF0000;
}

This is now more flexible that the previous inline style. We can easily change the colour via the code in the <style> and because this is now a class selector we could easily apply the class to some other content in the page. For example, place a <span> around the text ‘web developers’ in index.html and assign the highlight class to the <span>.

Save and review your file. Both pieces of text in the span.highlight tags appear red.

Clone this wiki locally