Sub topic 3
Seeing Which Styles Apply with Developer Tools
Assume you know basic HTML, CSS selectors, and file paths. Browser developer tools help you inspect the cascade: the process that chooses a winning declaration when several rules set the same property.
Inspecting the winning rule
Right-click an element and choose Inspect. In the Styles panel:
- Active declarations are shown normally.
- Overridden declarations are crossed out.
- Each declaration includes its stylesheet, selector, and line number.
- Inline declarations usually appear in an
element.stylesection. - The Computed panel shows the final value after inheritance and the cascade.
Use the filter box to find a property such as color. If a rule loses because of specificity or source order, the panel makes that reason easier to identify.
Choosing the right method
| Method | Best use | Main trade-off |
|---|---|---|
| Inline `style` attribute | One dynamic or exceptional element | Hard to reuse and often blocked by CSP |
| Internal `style` element | A single page or small prototype | Cannot be shared efficiently across pages |
| External stylesheet | Most multi-page sites and applications | Requires a correct URL and an extra resource |
Prefer an external stylesheet for shared design. Use internal CSS for page-specific rules. Reserve inline CSS for values generated at runtime or a deliberate exception.
Loading CSS with `@import`
An external stylesheet can load another stylesheet:
@import url("reset.css");
body {
margin: 0;
}Place @import before other rules. Separate link elements are usually easier to inspect and can let the browser fetch stylesheets more efficiently.
Performance: blocking and caching
Stylesheets can block the first render because the browser needs CSS to calculate layout and appearance. Keep critical CSS small. External files can still improve repeat visits because the browser can cache them and reuse them across pages.
Security: Content Security Policy
A Content Security Policy (CSP) controls where styles may come from. For example:
Content-Security-Policy: style-src 'self'This permits stylesheets from the same origin but blocks inline style attributes and style elements. A nonce or hash can allow specific inline styles. Avoid weakening the policy with 'unsafe-inline' unless the risk is understood.
Exercise
A paragraph is blue from an external rule, but a later internal rule sets it to green. Which color wins when both selectors have equal specificity?
Show answer
Green wins because the later declaration appears later in the cascade.