Cascading style, specificity and inheritance in CSS

Cascading style and specificity

CSS stands for cascadind style sheets and cascading simply means multiple styles can be applied or multiple rules can be applied to the same element. Now this rules may lead to conflicts though. To resolve such conflicts CSS knows a concept called specificity and there are clear rules included in the CSS specification that define how such conflict should be resolved and which type of selector has a higher specificity.

So cascading means multiple rules are applied to the same element. Specificity resolve conflicts arising from that fact and specificity then simply has the following order: the tag selector and also pseudo elements selectors have the lowest priority, the lowest specificity. Well actually, the universal selector, that star has the lowest priority but you rarely use that. So tag selectors have the lowest one then, a higher specificity is assigned to class and pseudo class as well as attribute selectors. So these three are on the same level and if we then have two conflicts here, simply the latter one in the same file wins. A higher specificity is assigned to ID selectors, so if an element has a tag, a class and an ID selector and they all set the color of that element, the ID selector would actually win no matter where it is positioned in the CSS file.

The highest priority however is assigned to inline styles, but we shouldn't use it. But if you add them, they will actually overwrite all other styles, they have the highest specificity. Now there are more rules connected to specificity, some advanced things connected to things like inheritance.

So tag selectors have the lowest specificity, inline styles have the highest. Now this doesn't mean that you should always use inline styles, it just means you should be aware of this and you should style your page cleverly by actually using all these types of selectors, maybe without inline styles though and simply be aware of how they overwrite each other and it's actually not hard to work with this correctly

Inheritance

Inheritance means that an element also inherits some style of the parent element. Some styles, especially the font related styles are passed down to child. However, inheritance has a very low specificity, inheritance always comes at the bottom even below the browser defaults. So inheritance is an important conncept for passing styles down without explicitly selecting an element and especially for things like font sizes, font families, this is extremely useful because you tipically want to have one and the same style for the majority of the text on your screen and setting this in the body tag is a great way.

Inheritance works but any direct selector has a higher specificity and therefore will overwrite your inheritance if it defines the same property

Category: HTML & CSS Tag: #css