Did you find this useful?
Socialize it today.


CSS Class and ID Selectors

Wednesday, March 07, 2012

tags CSS

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 in 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>


Results

Blue text in this paragraph

Red text in this paragraph



Try it!. You can practice your HTML skills by using our online HTML Editor. 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>


Results

Blue text in this heading

Red text in this 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>


Results

This text will be centered and formatted as red text.

This text will not be centered and no color will be applied.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS: The Complete Reference HTML CSS and JavaScript Editor CSS: The Missing Manual