1 answer
Inline styles win because, in the CSS cascade, a declaration written in the element's own style attribute has the highest specificity and is applied last, closest to the element.
The cascade. When several rules set the same property on an element, the browser decides which one to apply by (1) importance (!important), (2) specificity, and (3) source order (the later rule wins if specificity is equal). The usual order from lowest to highest priority is:
- Browser default (user-agent) styles
- External style sheet (
<link rel="stylesheet">) and internal style sheet (<style>in the head) — these two compete by specificity, and if equal, whichever comes later in the document wins - Inline style (
style="..."attribute)
Specificity reason. Specificity is counted as (inline, IDs, classes/attributes/pseudo-classes, elements). An inline style counts as (1, 0, 0, 0), which beats any selector in a style sheet, even an ID selector (0, 1, 0, 0).
Example
/* style.css (external) */
p { color: blue; }
<style> /* internal */
#intro { color: green; }
</style>
<p id="intro" style="color: red;">Hello</p>
The text appears red: the browser default (black) is overridden by the external rule (blue), which is overridden by the more specific internal ID rule (green), which is overridden by the inline style (red).
Exception: a style-sheet rule marked !important (e.g. p { color: blue !important; }) overrides a normal inline style. Because inline styles mix content with presentation and are hard to maintain, they are best used only for quick, one-off changes.
Your answer
Log in or create a free account to answer this question.