CSS Selectors

 

In CSS, selectors are patterns used to select the element(s) you want to style. There are a few CSS selectors available but the most common ones are class and id.

 

 

.class Selector

 

The class selector is used to specify a style for a group of elements. This allows you to set a particular style and apply it to multiple elements. The class selector starts with a dot and uses the HTML class=" " attribute to target an element. For instance if would like to have some of the text in the page to be in red, you can create a .red class then apply it anywhere in the text by inserting the class="red" attribute inside the opening tag of that element. If the element does not have a tag, you can use a <span> tag.

 

In the code below we are applying red color to the word "example":

 

<html>

<head><style type="text/css">
.red {color: #ff0000;}
</style>

</head>

 

<body>
This is an <span class=”red”> example </span> of class selector.
</body>

</html>

 

 

Result:

 

This is an example of class selector.

 

 

#id Selector

 

The id selector is used to specify a style for a single, unique element unlike the Class selector which works on multiple elements. The id selector starts with a # sign and uses the id=" " attribute to target an element. The id selector is particularly used for styling <div> tags.

 

Example:

 

<html>
<head><style type="text/css">
#box1 {
width: 300px;
height: 50px;
background-color: #ccff00;
}
</style></head>


<body>
<div id="box1">
This is a box.
</div>
</body>

</html>

 

 

Result:


This is a box.

 

 

 

Compound CSS Rules

 

Compound CSS rules are use when you need to combine more than one rule to style an element within another element. For example, if you want to style a paragraph inside the <div id=”box1”> but not to affect the the paragraphs in the document you can use:

 

#box1 p {
color: #F00;
}

 

 

Buy "Digest Web Design" PDF Book

 

All the information on this website is also provided in a PDF book for only $30.
Click here to buy.

 

 

<<    Previous Page                                                                    Next Page    >>