What\'s the difference between An id must be unique in the whole page. A class may apply to many elements. Sometimes, it's a good idea to use ids. In a page, you usually have one footer, one header... Then the footer may be into a div with an id <div id="footer" class="..."> and still have a class CSS selector space actually allows for conditional id style: will render as expected. Why would you do this? Sometimes IDs are generated dynamically, etc. A further use has been to render titles differently based on a high-level ID assignment: Personally, I prefer longer classname selectors: as I find using nested IDs to differentiate treatment to be a bit perverse. Just know that as developers in the Sass/SCSS world get their hands on this stuff, nested IDs are becoming the norm. Finally, when it comes to selector performance and precedence, ID tends to win out. This is a whole other subject. In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”). The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one. In advanced development ids we can basically use JavaScript. For repeatable purposes, classes come handy contrary to ids which supposed to be unique. Below is an example illustrating the expressions above: Now you can see in here The concept is inheritance in an OOP language. IDs are unique. Classes aren't. Elements can also have multiple classes. Also classes can be dynamically added and removed to an element. Anywhere you can use an ID you could use a class instead. The reverse is not true. The convention seems to be to use IDs for page elements that are on every page (like "navbar" or "menu") and classes for everything else but this is only convention and you'll find wide variance in usage. One other difference is that for form input elements, the In years gone by IDs were also preferred because they're easily accessible in Javascript (getElementById). With the advent of jQuery and other Javascript frameworks this is pretty much a non-issue now.
h1#my-id {color:red}
p#my-id {color:blue}
body#list-page #title {font-size:56px}
body#detail-page #title {font-size:24px}
body#list-page .title-block > h1 {font-size:56px}
<div id="box" class="box bg-color-red">this is a box</div>
<div id="box1" class="box bg-color-red">this is a box</div>
box
and box1
are two (2) different <div>
elements, but we can apply the box
and bg-color-red
classes to both of them.<label>
element references a field by ID so you need to use IDs if you're going to use <label>
. is an accessibility thing and you really should use it.