Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ampersands in CSS within an XHTML document and still validate?

I'm working on a framework that uses an image controller to load all images from a directory outside the webroot, and this includes images used within the CSS. Eg:

background: #FFF url(example.org/index.php?sect=loadimg&img=branding.jpg) top left repeat-x;

This seems to work ok, but my xhtml validator doesn't like the ampersand usage in the CSS, and using & instead doesn't work at all. So would anyone know if it is legal to use an ampersand like this in the stylesheets? If not, is there any other way to accomplish the same image request?

like image 524
Spoonface Avatar asked May 18 '11 18:05

Spoonface


1 Answers

The validator will complain only if you're validating against an XHTML doctype. Having unescaped HTML characters within <style> and <script> elements should still be considered valid in normal HTML (both 4.01 and 5).

The ideal solution is to move your CSS to an external stylesheet and include it using a <link> or an @import.

If your styles must reside in <style> tags, though, you can add CDATA sections within your <style> tags:

<style type="text/css">
/* <![CDATA[ */

/* Your CSS here */

/* ]]> */
</style>

This will cause all HTML special characters within that section to be treated literally, and your XHTML document to validate.

Note that the CDATA section delimiters are just <![CDATA[ and ]]>; they're wrapped in /* CSS comments */ so browsers don't try to interpret them as CSS.

CDATA sections in XHTML are covered by the spec.

like image 100
BoltClock Avatar answered Nov 15 '22 00:11

BoltClock