CSS class vs id

Friday 26th, Oct, 2018 | #CSS #CSS2 / CSS3


Class and Id are two ways to describe HTML/XHTML basic elementes like <div>,<p>,<ul>

A class selector is name preceded with (".") and ID selector preceded by ("#").




#selector {
    color: green;
}

.selector {
    color: red;
}


css class and id difference

ID's identify one element (Unique), each page can have only one element with that ID

Class can be used to identify multiple elements. and can use multiple classes on the same element.


<style>
.myclass {
    color: green;
}
.otherclass {
    color: green;
    background-color: red;    
}
</style>

<div class="myclass otherclass"></div>
<div class="myclass"></div>
<div class="myclass"></div>

can also css class and id selector together


<style>
.myclass {
    color: green;
}
#myid {
    color: green;
    background-color: red;    
}
</style>

<div id="myid" class="myclass"></div>

</code></pre>

Get element inside element by class and ID - JavaScript


var x =  document.getElementsByClassName("myclass");
var y =  document.getElementsById("myid");