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

Nonces for Inline Styles

Apply nonces to inline style tags and style attributes to allow specific styles under strict CSP.

Nonces for Inline Styles

What you'll learn: How to use cryptographic nonces to safely allow specific inline styles under a strict Content Security Policy.

Just as you learned to add nonces to inline <script> tags to permit them under CSP, the same technique applies to inline CSS. When you set a style-src directive that blocks 'unsafe-inline', you can still allow specific inline styles by matching their nonce values.

Why Nonces for Styles Matter

A strict CSP blocks inline styles by default to prevent attackers from injecting malicious CSS (which can exfiltrate data or create phishing overlays). However, legitimate inline styles are sometimes necessary for dynamic UI or third-party components. Nonces let you allowlist specific inline styles without opening the door to all inline CSS.

How It Works

Generate a unique, unpredictable nonce on the server for each page load (just like for scripts). Then:

  1. Add the nonce to your CSP header:

    Content-Security-Policy: style-src 'nonce-abc123xyz789'
    
  2. Apply the nonce to inline <style> tags:

    <style nonce="abc123xyz789">
      .highlight { background: yellow; }
    </style>
    
  3. Apply the nonce to style attributes:

    <div style="color: red;" nonce="abc123xyz789">
      Important text
    </div>
    

Without the matching nonce, the browser will block the inline style. With it, the style executes safely because only your server could have generated that specific nonce value.

Key Takeaway: Nonces allow you to maintain a strict style-src policy while selectively permitting trusted inline <style> tags and style="" attributes by matching server-generated cryptographic tokens.