CSS Class Selector v/s ID Selector:
Class | Id |
We can apply a class to various elements. | We can only apply it to one specific element. |
Starts with “.” followed by the name of the class. | Starts with “#” symbol followed by a unique id name. |
We can attach multiple class selectors to an element. | We can attach only one ID selector to an element. |
Syntax: .class { // declarations of CSS } | Syntax: #id { // declarations of CSS } |
ID selector Example:
<!DOCTYPE html> <html> <head> <style> #abc { text-align: center; color: blue; font-size: 25px; background-color: pink; } </style> </head> <body> <p id=”abc”>affect</p> <p id=”abc”>no affect</p> </body> </html> |
Class selector Example:
<!DOCTYPE html> <html> <head> <style> .abc { text-align: center; color: red; font-size: 25px; background-color: cyan; } </style> </head> <body> <p class=”abc”>affect</p> <p class=”abc”>no affect</p> </body> </html> |
We cannot apply multiple IDs to single element where as we can apply multiple classes to one element.
<!DOCTYPE html> <html> <head> <style> .abc { text-align: center; color: red; } .xyz { font-size: 50px; } #p1 { text-align: center; color: blue; } #p2 { font-size: 50px; } </style> </head> <body> <p class=”abc xyz”>affect</p> <p id=”p1 p2″>no affect</p> </body> </html> |
We can apply Class selector to particular Element by specifying element also:
<!DOCTYPE html> <html> <head> <style> p.abc { text-align: center; color: red; } </style> </head> <body> <h1 class=”example”>This heading is not effected.</h1> <p class=”example”>This paragraph is blue and center-aligned.</p> </body> </html> |