Tech 101: Understanding CSS classes vs. IDs
When writing CSS, you will find yourself needing to single out HTML elements or groups of HTML elements to apply styles to. In order to do this, you will need to give those HTML elements a CSS class or ID.
When writing CSS, you will find yourself needing to single out HTML elements or groups of HTML elements to apply styles to. In order to do this, you will need to give those HTML elements a CSS class or ID.
CSS Classes
In CSS, a class is a group of elements that are the same or similar. You can have as many elements as you want in a class. And each element can be the member of multiple classes. Every class has CSS attributes (like color and font-size) that are specific to that class.
CSS classes are similar to a real-life class. A class is a group of students, who often share certain similarities: similar ages, area codes, interests, or life goals.
How to add a class to your HTML element:
<div class="class">
How to use a class in your CSS:
.class {
width:100px;
height:300px;
background:purple;
}
Each HTML element can have multiple CSS classes.
<div class="class another-class">
CSS IDS
An ID is a singular identifier of one HTML tag. You can only have one HTML tag per ID and each HTML tag can only have one ID. Each ID has a specific set of CSS attributes that only apply to that one element.
To go back to our real-life class example, even if a group of students shares many attributes, each student has their own Social Security number that identifies them and only them.
How to add an ID to your HTML element:
<div id="id">
How to use them in your CSS:
#id {
width:200px;
height:200px;
background:blue;
}
Cocktail Party Fact
In CSS, HTML tags, classes, and IDs each have their own numerical value. IDs have the highest numerical value, followed by classes, and then HTML elements themselves. If an HTML element has two styles applied to it that conflict, CSS defaults to the higher value. Check out this CSS specificity calculator.
Adda Birnir
Category: Blog, Entry Level Tech Jobs, Front End Developer, Full Stack Developer, HTML and CSS, Learn to Code