CSS Tutorial
CSS - Introduction CSS - How CSS works? CSS - Syntax CSS - Colors CSS - Backgrounds CSS - Borders CSS - Margins CSS - Padding CSS - Height/Width CSS - Box Model CSS - Text CSS - Fonts CSS - Icons CSS - Cursor CSS - Outline CSS - Links CSS - Lists CSS - Tables CSS - Display CSS - Overflow CSS - Position CSS - Float CSS - Align CSS - Opacity CSS - Combinator CSS - Pseudo Classes CSS - Pseudo Elements CSS - Attribute Selector CSS - Buttons CSS - Pagination CSS - Navigation Bar CSS - Dropdowns CSS - Specificity CSS - Transition
CSS Advanced
CSS - Rounded Corners CSS - Border Image CSS - Background CSS - Gradients CSS - Shadow CSS - Text Effects CSS - 2D Transform CSS - 3D Transform CSS - Animation CSS - Object-fit CSS - Box Sizing CSS - Filters CSS - Style Images CSS - Variables CSS - Media Queries CSS - Flexbox Layout CSS - Grid Layout
CSS Responsive
RWD - Introduction RWD - Grid View RWD - Media Queries RWD - Images
CSS References
CSS - Reference CSS - Selectors CSS - Functions CSS - Units CSS - Animatable CSS - Entities

CSS Specificity

What is Specificity?

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

Specificity is a common reason why your CSS-rules don't apply to some elements, although you think they should.

How is specificity calculated?

Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector.

The following list of selector types increases by specificity:

  • Elements and pseudo-elements
  • Classes, attributes, and pseudo-selectors
  • IDs
  • Inline styles

When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element.

Specificity only applies when the same element is targeted by multiple declarations.

Specificity Rules

Class selectors have a higher specificity compared to any number of element selectors:

In the following example we defined 2 different style declarations for a DIV- (using element selector and class selector):

Run code

ID selectors have a higher specificity than class selectors:

Run code

Inline style has the highest specificity:

Run code

The !important rule

When an !important rule is used on a style declaration, this declaration overrides any other declarations.

Although technically !important has nothing to do with specificity, it interacts directly with it.

Using !important, however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets.

When two conflicting declarations with the !important rule are applied to the same element, the declaration with a greater specificity will be applied.

Run code