CSS selector

What are the CSS selectors

We can set styles for a HTML element by using tag name as the selector. CSS supports to create our own selectors.

There are two types of selectors we can create. One is called "id" and other other is "class".

Write id selector

The id selector specifies a style for a single unique element. When applying the style we use the id attribute of the HTML element. The id select is defined with a "#".

The following CSS creates a id named para1 and sets its color.


#para1
{
   color:red;
}

Let's put the id selector to work.


<!DOCTYPE HTML> 
<html> 
    <head> 
        <style type="text/css"> 
        #myPara<!--  www .j  av a2 s.  c  o m-->
        {
           text-align:center; color:red;
        }
        </style> 
    </head> 
    <body> 
        <p id='myPara'>Visit the website</p> 
    </body> 
</html>

Click to view the demo

We use the id attribute to add to id selector to an element.

The code above generates the following result.

CSS selector

Use class Selector

The class selector selects a group of elements. If we want to apply styles to a group of elements we should use class selector.

The class selector uses the HTML class attribute, and is defined with a ".".

In the example below, all HTML elements with class="center" will be center-aligned:


.center {text-align:center;}

Let's put the class selector to work.


<!DOCTYPE HTML> 
<html> 
    <head> 
        <style type="text/css"> 
        .center {text-align:center;}<!--from   ww  w . j  a  v  a 2  s .  c  o m-->
        </style> 
    </head> 
    <body> 
        <p class='center'>Visit the website</p> 
        <p class='center'>Visit the website</p> 
        <h1 class='center'>Visit the website</h1> 
    </body> 
</html>

Click to view the demo

In the code above we create a style with class selector. Then we use it with two paragraph tags and one heading tag. We can use the same style for different tags.

The code above generates the following result.

CSS selector