CSS Specificity
Jhosep
Posted on August 18, 2023
In CSS, the level of importance of styles applied to an element is governed by specificity. it determines which CSS rule set takes precedence when multiple rules are applied to the same element.
Here are some examples where it applies:
Inline Styles: These have the highest specificity and therefore have the highest priority. They are applied directly to an element within its style attribute.
ID Selectors: These have a higher specificity than class and element selectors. But if using an ID to style multiple elements, it's important to remember that it's good practice to keep unique IDs throughout the page.
Selectors class: They are less specific than IDs but more specific than element selectors. You can apply the same class to multiple elements and apply similar styles to all of them.
Element Selectors: They are the least specific. These affect all elements of the same type (eg all paragraphs, all headings (p, h1), etc.) and can easily be affected by more specific rules.
When multiple styles are applied to the same element and there are conflicts, the rule with the highest specificity will prevail. If two or more rules have the same specificity, the last rule found in the code will be applied.
It is important to understand these hierarchies of specificity so that you can control and predict how styles will be applied on your web page.
Veamos codigo
<style>
#id-selector {
color: blue;
}
.selector-class {
color: green;
}
</style>
<div id="id-selector" class="selector-class">This div has an ID and a class
</div>
What color do you think is painted in the div? Well, blue since the id-selector has greater specificity.
If an inline style was put in the code, it would take that value that we put in it and ignore the others.
Posted on August 18, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.