CSS SETUP AND SELECTORS ID Name. Is the ID always overrides the CLASS attribute in CSS?

Hi,
I was wondering when you add an ID attribute to an HTML element but there is also a CLASS attribute to the same element and you want your CSS selector point to them, which one will be used? CLASS or ID?

In the lesson, it says “If an HTML element needs to be styled uniquely (no matter what classes are applied to the element), we can add an ID to the element.”

So, does it mean that the if in our CSS we refer to the ID of a given element it will always override the CLASS attribute? Can it happen vice versa where the CLASS would override the ID attribute?

Thank you!

Sorry, in the next lesson I got my answer. It says " Since IDs override class and tag styles, they should be used sparingly and only on elements that need to always appear the same."

The lesson in the link provided:

https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-web-development-fundamentals/modules/fecp-learn-css-selectors-and-visual-rules/lessons/css-setup-selectors/exercises/id-name

I wrote a detailed answer here:

Oes a “chained” selector have a higher specificity than a class or id selector? For example, which selector would “win”: `.special` or `h1.special` or `#special`?

This is about resolving conflicting css properties, so if you have an element with both a class and id:

<div class="red" id="green">I am green</div>

#green {
   color: green;
}

.red {
  color: red;
}

the text will be green. ids have higher specificity.

If you have:

<div class="red" id="green">I am green</div>

#green {
   color: green;
}

.red {
  color: red;
  font-size: 40px;
}

the font-size will be 40px, the id doesn’t specify a font-size, so the class font-size will be applied

1 Like