style-src Directive Configuration
Configure the style-src CSP directive to control stylesheet loading and inline styles. Learn how to handle CSS frameworks, styled-components, and CSS-in-JS solutions.
Detailed Explanation
The style-src Directive
The style-src directive controls which stylesheets and inline styles a page is allowed to use. While less commonly exploited than scripts, malicious CSS can still be used for data exfiltration and UI redressing attacks.
Basic Configuration
Content-Security-Policy: style-src 'self' https://fonts.googleapis.com
This allows stylesheets from the same origin and Google Fonts. Inline styles (<style> tags and style attributes) are blocked.
The Inline Styles Challenge
Many modern CSS frameworks and libraries inject inline styles:
- CSS-in-JS (styled-components, Emotion) generates
<style>tags at runtime - Component libraries (Material UI, Chakra UI) use inline styles for dynamic theming
- Animation libraries manipulate
styleattributes directly
To support these, you often need to allow inline styles. The options from most to least secure are:
1. Nonces (recommended)
Content-Security-Policy: style-src 'nonce-abc123'
The CSS-in-JS library must inject the nonce into every <style> tag it creates.
2. Hashes
Content-Security-Policy: style-src 'sha256-...'
Only practical for static <style> blocks whose content does not change.
3. unsafe-inline (last resort)
Content-Security-Policy: style-src 'self' 'unsafe-inline'
Allows all inline styles. Use only when nonces and hashes are not feasible.
style-src-elem and style-src-attr
CSP Level 3 splits style-src into two sub-directives:
style-src-elem— controls<style>elements and<link rel="stylesheet">style-src-attr— controls inlinestyleattributes on HTML elements
Content-Security-Policy: style-src-elem 'self' 'nonce-abc123'; style-src-attr 'unsafe-inline'
This combination allows nonced stylesheets while permitting inline style attributes — a practical middle ground for many applications.
Google Fonts Example
Content-Security-Policy: style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com
Note that Google Fonts requires two origins: fonts.googleapis.com for CSS and fonts.gstatic.com for font files (controlled by font-src).
Use Case
Configuring style-src is critical for applications that use CSS frameworks or CSS-in-JS libraries. A React app using styled-components needs nonce support in style-src. A static site loading only external stylesheets can use a strict style-src 'self' policy. Understanding the tradeoffs between security and framework compatibility helps developers make informed decisions.