Skip to content
Related Articles

Related Articles

How to secure cascading style sheets ?

Improve Article
Save Article
  • Last Updated : 14 Jun, 2022
Improve Article
Save Article

Before learning how to secure cascading style sheets, let us first explore what are the threats that would cause through cascading stylesheets.

Threat 1: Let us assume that we are using embedded/internal CSS in our code and you are allowing a user some CSS customization, then there is a chance that the attacker could inject a JavaScript code by closing the style tag in the customizable internal CSS. 

Refer to the below snippet for better understanding. 

Code snippet:


/* If you have added the flexibility to 
   customize the CSS by the user */

/* Customizable CSS


The attacker could add a malicious JavaScript code by closing the style tag and adding a script tag as shown below.



// Some malicious JavaScript code


This occurs in a rare case as a user might not be given the flexibility to customize the cascading stylesheets always.

Threat 2: Suppose you are logged in to a website and that the site displays some sensitive information like social-security-number (ssn), then there is a chance that the attacker can get those sensitive information by using the CSS Attribute selectors. 


input#ssn[value="999-888-777"] { 
    background-image: url(

How to secure cascading stylesheets ?

Proper access control level: Keep the CSS away from the access control level. By the term “Access control level” it means that the normal user will have a different CSS file while the administrator has a different CSS file. Proper care should be taken for those respective CSS files that are accessible only for a user with the proper access control level or authentication.

CSS Obfuscation: The method CSS Obfuscation is to make the CSS unclear or confusing to the attacker. CSS Obfuscation can be done by using the following websites.

Implementing the Content Security Policy (CSP): Content Security Policy (CSP) helps to detect many types of attacks like data injection attacks and cross site scripting (XSS). By this way, an extra layer of security is given from data theft, malware distribution and replacing your own contents to some stolen websites.

You can configure CSP by using the meta tag as shown below.

<meta http-equiv="Content-Security-Policy"
charset="UTF-8" content="default-src 'self';
img-src 'self';">

Scanning website with vulnerability scanner: Scanning your website with a vulnerability scanner is a best practice, these scanner not just detect CSS or XSS injections, but also showcase other possible vulnerabilities in your website.

Some of the online vulnerability scanners are

These are some of the techniques for securing your cascading stylesheets.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!