Content Security Policy (CSP)
Examples


CSP Inline Styles

When you enable CSP, it will block inline styles, but there are some ways that you can allow inline styles and still use Content Security Policy.

Inline Styles are Blocked by Default with Content Security Policy

When you have a Content-Security-Policy header defined, the browser will automatically block inline style (unless you implement one of the workarounds specified below), such as:

<style>
	.red { color: red }
</style>

Or

<div style="color:red;">Red Text</div>

You might see something like this as a result:

content security policy: the page’s settings blocked the loading of a resource at inline (“style-src”).

Or you might see this:

content security policy: the page’s settings blocked the loading of a resource at inline (“default-src”).

Or

refused to apply inline style because it violates the following content security policy directive

Allow Inline Styles using a Nonce

One of the easiest ways to allow style tags when using CSP is to use a nonce. A nonce is just a random, single use string value that you add to your Content-Security-Policy header, like so:

style-src css-cdn.example.com 'nonce-r@nd0m';

Assuming our nonce value is r@nd0m (you need to randomly generate a new nonce for every HTTP request), we can now use an inline style tag like this:

<style nonce="r@nd0m">
	.red { color: red }
</style>

Allow Inline Scripts using a Hash

A second approach to allow inline scripts is to use a hash, with this approach you compute the hash of your JavaScript code, and put the value in our CSP policy:

style-src css-cdn.example.com 'sha256-xyz4zkCjuC3lZcD2UmnqDG0vurmq12W/XKM5Vd0+MlQ='

Other methods

The unsafe-inline source list keyword can be used to allow inline styles, but this also removes much of the security protection that you gain when you enable CSP.

CSP Level 3 (newest browsers) support a source list value: unsafe-hashes which can be used to allow inline style attributes on HTML tags.