Course contentsShow
← Web Development
Lesson 2843 of 2,98251. Content Security PolicyFree lesson

The style-src Directive

Restricting CSS sources with style-src to prevent style-based attacks and unauthorized stylesheets.

The style-src Directive

You'll learn how to control which stylesheets your page can load using the style-src Content Security Policy directive.

What style-src Controls

Just as script-src guards against malicious JavaScript, the style-src directive restricts where your page can load CSS from. This prevents attackers from injecting malicious stylesheets that could hide legitimate content, create fake login forms that look authentic, or exfiltrate data through carefully crafted CSS selectors.

Think of style-src as a bouncer for your page's styling: it checks every stylesheet's origin and only allows trusted sources through the door.

How It Works

The style-src directive follows the same pattern as other CSP directives. You specify allowed sources in your CSP header:

Content-Security-Policy: style-src 'self' https://fonts.googleapis.com;

This policy allows:

  • Stylesheets from your own domain ('self')
  • Stylesheets from Google Fonts

It blocks everything else, including:

  • Inline <style> tags
  • Inline style="" attributes
  • Stylesheets from untrusted domains

Common Sources

  • 'self' — Your own domain's stylesheets
  • 'unsafe-inline' — Allows inline styles (weakens security, avoid if possible)
  • Specific domains — https://cdn.example.com
  • 'nonce-' or 'sha256-' — Allow specific inline styles using cryptographic verification

The Inline Style Problem

If you need inline styles, use nonces (random tokens) instead of 'unsafe-inline':

Content-Security-Policy: style-src 'self' 'nonce-xyz123';

Then in your HTML:

<style nonce="xyz123">
  .special { color: red; }
</style>

Key Takeaway: The style-src directive prevents style injection attacks by restricting which CSS sources your page trusts, protecting users from phishing attempts and content manipulation through malicious stylesheets.