CSS id and class Selectors
If you want to set CSS styles for HTML elements, you need to use the "id" and "class" selectors in the elements.
id Selector
The id selector can specify styles for an HTML element marked with a specific id.
HTML elements set the id selector with the id attribute, and in CSS, the id selector is defined with a "#".
The following style rule applies to an element with the attribute id="mydiv":
<div id="mydiv">This is a sample</div>
#mydiv
{
text-align:center;
color:red;
}
Do not start the id attribute with a number, as ids starting with numbers do not work in Mozilla/Firefox browsers.
class Selector
The class selector is used to describe a style for a group of elements. Unlike the id selector, the class can be used on multiple elements.
The class selector is represented by the class attribute in HTML, and in CSS, a class selector is shown with a dot ".".
In the following example, all HTML elements with the class "center" are centered:
.center {text-align:center;}
You can also specify a specific HTML element to use the class.
In the following example, all p elements with class="center" will have their text centered:
p.center {text-align:center;}
Multiple class selectors can be separated by spaces:
.center { text-align:center; }
.color { color:#ff0000; }
The first character of a class name cannot be a number! It will not work in Mozilla or Firefox.
In summary, id, class, and attribute selectors are three commonly used CSS selector attributes. By using them properly, we can select and style specific elements in a web page.