Understanding CSS Selector Specificity: Which Rule Wins?
This article explains how CSS selector specificity is calculated using a four‑digit weighting system, shows the numeric values assigned to different selector types, and demonstrates how to determine which of two conflicting rules will actually style an element.
Consider the following HTML snippet:
<div id="content">
<p id="title">Hello world</p>
</div>and two CSS rules that both set the color of the p element:
#title { color: red; } #content p { color: blue; }Only one rule will be applied, and the decision depends on CSS selector specificity.
CSS assigns each selector a four‑part numeric value (a.b.c.d) where a is the highest weight. The larger the number, the higher the priority. The four levels are:
Inline style (style attribute): 1,0,0,0
ID selector (#id): 0,1,0,0
Class selector, attribute selector, pseudo‑class (:link, :hover, etc.): 0,0,1,0
Element (type) selector (e.g., div, p): 0,0,0,1
Universal selector (*), :not pseudo‑class, and combinators (>, +, ~) have no weight: 0,0,0,0
Examples:
(1) ul#nav li.active a contains three element selectors, one ID selector, and one class selector. Adding the values gives 0,1,1,3, so this selector outranks a rule with 0,0,1,3.
(2) #footer *:not(nav) li includes one ID selector, one universal selector, one :not pseudo‑class, and two element selectors, resulting in a total specificity of 0,1,0,2.
(3) html > body div [id="testid"] ul li > p comprises six element selectors, one attribute selector, and two combinators, giving a specificity of 0,0,1,6.
By converting selectors to their numeric specificity, developers can predict which rule will be applied when multiple selectors target the same element.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
