Course contentsShow
← Web Development
Lesson 2900 of 2,98252. Frontend SecurityFree lesson

CSS Context Encoding

Preventing XSS through style attributes and CSS expressions by proper encoding.

CSS Context Encoding

What you'll learn: How to safely encode user data when inserting it into CSS contexts to prevent XSS attacks through style attributes and CSS expressions.

Why CSS Needs Special Encoding

Even though you've already learned HTML, JavaScript, and URL context encoding, CSS has its own unique syntax and attack vectors. Attackers can exploit style attributes and CSS rules to execute malicious code by breaking out of the CSS context or injecting dangerous properties like expression() (older IE) or using url() with javascript: protocols.

The Attack Surface

CSS contexts appear in two main places:

  • Inline style attributes: <div style="color: USER_INPUT">
  • Style tag content: <style>.class { color: USER_INPUT; }</style>

An attacker might try injecting something like red; background: url('javascript:alert(1)') or red'}; </style><script>alert(1)</script>.

Proper CSS Context Encoding

When inserting user data into CSS:

  1. Validate first: Only allow expected values (like hex colors or specific keywords)
  2. Encode CSS metacharacters: Escape characters like {, }, ;, \, quotes, parentheses, and angle brackets
  3. Use CSS escape sequences: Replace dangerous characters with their \HEX equivalents (e.g., < becomes \3C)
  4. Avoid dynamic property names entirely: Never let users control CSS property names
  5. Prefer allowlisting: If possible, map user input to predefined safe values rather than direct insertion

For style attribute values specifically, also apply HTML attribute encoding as a second layer since the attribute itself is HTML context.

Key Takeaway: CSS context encoding requires escaping CSS metacharacters and using CSS escape sequences to prevent attackers from breaking out of style contexts or injecting dangerous CSS properties—always validate and prefer allowlisting over direct insertion.