Class and ID in CSS
Class and ID in CSS
Id and Class Selectors
Id and class selectors are mainly used for apply css on one or more than one Html elements at a time. We can apply css on any Html elements by using these two selectors id and class .
Advantage of id and class
- Code Re-Usability
- The main advantage of id and class no need to write code again and again.
id Selector
The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the Html element, and is defined with a # sign.
In below example we apply css on <p> tag with id="para1":
Syntax
#para1 { text-align:center; color:red; }
Example
<html> <body> <style> #center { text-align:center; } </style> <h1 id="center">This is heading</h1> <p id="center">This is paragraph</p> </body> </html>
Result
This is heading
This is paragraph
Note: Do not start an ID name with a number. Because It will not work in Mozilla/Firefox browser.
class Selector
The class selector is used to specify a style for a group of elements. Unlike the id selector. This allows you to set a particular style for many Html elements with the same class. The class selector uses the Html class attribute, and is defined with a . (dot) sign.
In below example declare a class with name "center" (.center) which is used many Html attribute for display that particular element in center
Syntax
.center { text-align:center; }
Example
<html> <body> <style> .center { text-align:center; } </style> <h1 class="center">This is heading</h1> <p class="center">This is paragraph</p> </body> </html>
Result
This is heading
This is paragraph
You can also specify only specific Html elements should be affected by a class. In below example , all <p> elements will be display in center because here we apply css with <p> tag.
Example
p.center { text-align:center; }
Note: Do not start a class name with a number. This is only supported in Internet Explorer.