Course contentsShow
← Security
Lesson 660 of 3,05214. Web Security - XSS and Content InjectionFree lesson

style-src and CSS Injection Prevention

Restricting stylesheet sources and preventing CSS-based attacks through proper style directives.

style-src and CSS Injection Prevention

You'll learn how to lock down stylesheet sources to prevent attackers from injecting malicious CSS into your web application.


While most XSS discussions focus on JavaScript, CSS can also be weaponized. Attackers can inject malicious stylesheets to steal data (through selectors that leak information via background images), create convincing phishing overlays, or even exfiltrate form data. The style-src Content Security Policy directive controls where CSS can be loaded from, just like script-src does for JavaScript.

How style-src Works

The style-src directive specifies valid sources for stylesheets (<link> tags), inline <style> blocks, and CSS-related attributes. Without it, attackers who find an injection point might add:

  • Malicious inline styles that overlay fake login forms
  • External stylesheets from attacker-controlled domains
  • CSS that exfiltrates data through attribute selectors

Example policy:

Content-Security-Policy: style-src 'self' https://trusted-cdn.com

This allows styles only from your own domain and a specific CDN. Inline styles and style attributes are blocked by default.

Handling Inline Styles Safely

If you need inline styles (though it's better to avoid them), use 'unsafe-inline' (risky) or better yet, the nonce or hash approach:

Content-Security-Policy: style-src 'self' 'nonce-random123'

Then in your HTML:

<style nonce="random123">
  .header { color: blue; }
</style>

The nonce must be unique per request and unpredictable to attackers.

Why This Matters

CSS injection might seem harmless compared to JavaScript execution, but it can enable credential harvesting, UI redressing attacks, and data leaks through cleverly crafted selectors. Restricting style sources closes this attack vector.

Key Takeaway: The style-src directive prevents CSS injection attacks by controlling where stylesheets can be loaded from; combine with nonces or hashes to safely allow necessary inline styles while blocking attacker-controlled CSS.