How CSS Styles Conflicts Between Selectors ? (original) (raw)

Last Updated : 06 Jun, 2023

CSS conflicts between selectors occur when two or more selectors have conflicting styles applied to the same element, leading to unexpected results. In such cases, the browser has to decide which style to apply to the element. In this article, we'll understand what causes conflicting styles in CSS, and how to avoid and resolve them.

Causes of Conflicting Styles in CSS: There are several ways that conflicting styles can arise in CSS. One common cause is using multiple stylesheets, either external or internal, that have overlapping or conflicting rules. When styles from multiple stylesheets are applied to the same element, the browser will have to decide which style to use, leading to conflicts.

Another cause of conflicting styles is the use of multiple selectors that apply to the same element. If these selectors have conflicting styles, the browser will have to decide which style to apply, based on the specificity and order of the selectors.

There are three reasons for CSS style conflict:

Specificity: The more specific selector will override the less specific one. Specificity is calculated based on the number of elements, classes, and IDs in the selector. For example, the selector with an ID has a higher specificity than the one with a class, and the one with a class has a higher specificity than the one with an element.

Syntax:

p { color: blue; }

.special { color: red; }

Example: In this example, we have two conflicting styles for the color property applied to the same element p.special. However, the .special selector has a higher specificity than the p selector, so the color: red style will override the color: blue style.

HTML `