What to use <div class = "name"> or <div id = "name">?
I am learning HTML. Can someone please tell me what is the difference between class and id and when to use one over the other? It seems like they are doing the same
<!DOCTYPE HTML> <html> <head> <style> #mycolor1 {color: red;} .mycolor2 {color: red;} </style> </head> <body> <div id="mycolor1"> hello world </div> <div class="mycolor2"> hello world </div> </body> </html> They do not do the same. id used to target a specific element, classname can be used to specify multiple elements.
Example:
<div id="mycolor1" class="mycolor2"> hello world </div> <div class="mycolor2"> hello world2 </div> <div class="mycolor2"> hello world3 </div> Now you can immediately reference the div with the class name mycolor2 using
.mycolor2{ color: red } //for example - in css This will set all nodes with class mycolor2 to red .
However, if you want to specifically set mycolor1 to blue , you can target this way:
#mycolor1{ color: blue; } Read the specification for attributes and for CSS .
idmust be unique.classshould not beidhas higher (highest!) specificity in CSS- Elements can have several extraordinary classes (separated by spaces), but only one
id - Faster to select an item by its identifier when querying the DOM
idcan be used as an anchor target (using a request fragment) for any element.nameonly works with anchors (<a>)
Classes should be used when you have several similar elements.
Ex: Many divs displaying the lyrics of the song, you can assign them the lyrics class, since they are all similar.
The identifier must be unique! They are used to target specific items.
Ex: the userβs email input may have a txtEmail identifier - no other element should have this identifier.
To do this, it is simple: id is unique to only one element in the entire HTML document, but a class can be added to numerous elements.
In addition, ID properties take precedence over class properties.
Ides and classes are especially useful if you plan to use javascript or any of its infrastructure.
- The identifier selector is used when referring to one unique element.
- The class selector refers to a group of elements.
For example, if you have several buttons that look the same, you should use class = "mybutton" to have a consistent style.
In terms of performance:
CSS selectors match right to left .
Therefore, .myClass must be "faster" than #myID because it skips testing.
Performance frequency is negligible for regular sized pages, and you probably will never notice the difference, so basically this is roughly consistent.
Learn more about why css browsers match css selectors from right to left.