ID selectors, Class selectors
The role of a selector is to tell the browser to which style is applied to a specific element in an HTML document. Selectors are patterns used to select the HTML tags that you want to style. These patterns may range from simple element names to rich contextual patterns.
ID selector
ID selectors in CSS allow you to target elements (Tags) by their ID values. ID selectors are unique, so you can apply only to the content of one element. To reference an ID, you precede the ID name with a hash mark (#).
<html>
<head>
<style type="text/css">
#headingcolor {color: #FF0066;}
</style>
</head>
<body>
<h1 id="headingcolor">ID Selector</h1>
<h1>Without ID Selector</h1>
</body>
</html>
output
Class selector
The Class selector in CSS , which references the class attribute used on HTML elements. The Class selector begins with a dot(.) and followed by a class name which you choose.
Unlike the id attribute, multiple elements may share same class name, also an element may belong to more than one class.
Class in multiple elements
.textcolor {color: #FF0066;}
<p class="textcolor">Paragraph in class selector</p>
<h1 class="textcolor">Heading in Class Selector</h1>
In the above code multiple element shared same class name (.textcolor).
Multiple Classes in the same Element
.textcolor1 {color: #00FF00;}
.textcolor2 {color: #0000FF;}
<p class="textcolor1">Paragraph in class textcolor1</p>
<p class="textcolor2">Paragraph in class textcolor2</p>
In the above code same element implement different class name (.textcolor1 and .textcolor2).
Classes limit to one type of Element
Using Class Selector, you can limit the scope of the style sheet (CSS) rule to only that type of element.
In the above code, the selector matches any h1 elements that have a class attribute containing the word “textcolor”. If any other element have the class name “textcolor” wont work.
<html>
<head>
<style type="text/css">
h1.textcolor {color: #FF0066;}
.textcolor1 {color: #00FF00;}
.textcolor2 {color: #0000FF;}
</style>
</head>
<body>
<h1 class="textcolor">Heading </h1>
<h2 class="textcolor">Wrong implementation !! </h2>
<p class="textcolor1">Paragraph in class textcolor1</p>
<p class="textcolor2">Paragraph in class textcolor2</p>
<h1 class="textcolor2">Heading </h1>
</body>
</html>
output
From the above image, you can understand how to use Class Selectors in CSS effectively for styling HTML documents.