CSS Selectors


Id / Class / Tag / Inline Selector

If you want to set CSS styles in HTML elements, you can set "id" / "class" selectors in the elements.


Id Selector

The id selector can specify a specific style for the HTML element marked with a specific id.

HTML elements use id attributes to set id selectors, and id selectors in CSS are defined by "#".

The following style rules apply to the element attribute id="para1":

Example

#para1
{
    text-align:center;    
    color:red;
}

 Try It! 

Remark The ID attribute should NOT start with a number. IDs starting with a number will not work in Mozilla/Firefox browsers.


Class Selector

The class selector is used to describe the style of a group of elements. The class selector is different from the id selector. Class can be used in multiple elements.

The class selector is represented by the class attribute in HTML. In CSS, the class selector is represented by a dot ".":

In the following example, all HTML elements with the center class are centered.

Example

.center
{
    text-align:center;
}

 Try It! 

You can also specify specific HTML elements to use class.

In the following example, all p elements use class="center" to center the text of the element:

Example

p.center 
{
    text-align:center;
}

 Try It! 

RemarkNumbers cannot be used in the first character of the class name! It does not work in Mozilla or Firefox.


Tag Selector

In addition to the id and class selectors mentioned, the third type of selector is the tag selector, which uses HTML tags as the selector for CSS decoration.

Example

<style>
    h3{color:red;}
</style>
<h3>Find useful tutorials in tutorialfish.com</h3>

 Try It! 


Inline Selector

The fourth type of inline selector is to write CSS code directly inside the tag.

Example

<h3 style="h3{color:red;}">
    TutorialFish.com
</h3>

 Try It! 

These four CS selectors have modified priority:

Inline selector > id selector > class selector > tag selector


Extended Reading

When setting CSS styles in HTML tags, there are a variety of CSS selectors to choose from. You can refer to the CSS3 selector categorization on this site (including the new selectors in CSS3) to learn more about CSS selectors Content.