Computers & ProgrammingCSSWeb Development

CSS Class and ID Selectors

With CSS, there are many ways to apply styles across a web page, but you want to use a style on some of the elements in a web page, but not all instances of the same element.

Or, you may want to create a style that you can apply across several elements in a document, without configuring each style independently.

In some cases, you may event want to apply a style to a unique element only once in a page. To do this, you use the class and id HTML attributes. Class and id are global attributes that can be applied to just about every HTML element.

Class

The class selector allows you to set multiple styles to the same element in a web page. For example, you might want to have certain sections of your text formatted in a different color or a different size from the rest of the text on the page.

Here is an example where you have a need to format your paragraphs differently (CSS applied using internal style):

p.blue {
    color: blue;
}

p.red {
    color: red;
}

Example

<style type="text/css">
    p.blue {
        color: blue;
    }
    p.red {
        color: red;
    }
</style> 

<p class="blue">Blue text in this paragraph</p>
<p class="red">Red text in this paragraph</p>

If you want to apply the blue or red style across other elements, not just paragraphs, then use the class selectors without prefixing the class (be sure to leave the period . in place). Here is an example.

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

Example

<h3 class="blue">Blue text in this heading</h3>
<div class="red">Red text in this div</div>

ID

The id selector is used to specify a style for a single, unique element. While you can accomplish this with a class selector, the id selector is more appropriate for this scenario.

The id selector uses the id attribute of the HTML element and is defined by prefixing the id with a # symbol. In this example, we want to target a single paragraph in a document.

<style type="text/css">
    #centerText {
        text-align: center;
        color:red;
    }
</style> 

<p id="centerText">
    This text will be centered and formatted as red text.
</p>
<p>
    This text will not be centered and no color will be applied.
</p>

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top