Let’s briefly note the difference between assigning a class to an HTML tag and assigning an id to an HTML tag.
Follow along to learn when to use classes or Ids in CSS.
Class Vs Id
Both classes and ids can be targeted by CSS rules (classes with a . and id’s with a # symbol). For example, both paragraph tags below are styled the same, though one is referenced by class and the other by id.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Some Exciting Blue Text</title>
<link rel="stylesheet" href="main.css">
<p class="blue">This text will appear blue.</p>
<p id="also-blue">This text will also be blue. </p>
/* main.css */
This will output:
Some Exciting Blue Text
This text will appear blue.
This text will also be blue.
The important difference is that ids are unique, while classes are not unique. We can use the same class on multiple elements, while id’s must be unique to a single element on the page. Id’s may appear to work even when duplicated on the same page, but duplicate id’s will lead to inconsistent behavior and difficult-to-find bugs.
If in doubt, use a class.