Proximity and Precedence
What takes precedence in CSS:
embedded <style> rules, or...
external css file rules, or...
Many claims have been made that css rules in embedded <style> tags always take precedence over any <link> made to an external style sheet file (.css).
Actually, proximity to the html <body> determines it. For example:
- If the <style> element is beneath the <link> element, and therefore closer to the <body>, then its rules take precedence.
- This is because it is physically closer in the html code that it can affect.
- If the <link> element is closer, then its rules take precedence.
- The highest specificity will take precedence regardless of proximity.
- In this demo the rules have the same specificity: they both use the same selector.
Use the html in this page's code to prove that proximity controls format when specificity is equal.
- Right click anywhere on this page and select View Page Source, or Page Source, or a similar term. The page's source code will open up.
- Use Ctrl-A (⌘-A on Mac) to select all the code.
- Copy the code.
- Paste it into an empty plan text file such as a Notepad file in Windows or a TextEdit file on a Mac (but follow these directions first for Mac's TextEdit's settings).
- Save the file using any name you like, but be certain to end the file name with .html (NOT .txt).
- Remember where you saved it.
- Do not close the file.
- Go to your browser and press Ctrl-O (⌘-O).
- Find and open the file you just saved.
- If you cannot find it, you probably saved it without the .html file extension.
- Notice background color.
- Return to the file in Notepad or TextEdit
- Move the <link> element code above the <style> element.
- Save the file.
- Refresh your browser window (Ctrl-R or ⌘-R).
- The color ought to change.
- For an additional test, add the following to the <body> tag:
- It ought to take precedence due to both proximity and specificity (inline CSS as the highest specificity).
This demonstrates that rule proximity determines style, not whether the CSS is embedded or external.