Search code examples
cssxmlhtmldomsvg

Is CDATA necessary when styling an inline SVG?


I've read mixed things about this, so I'm hoping to get it sorted definitively.

If I have SVG markup that is inline within an HTML document, and I am styling it with CSS, do I need to wrap that CSS in commented out CDATA?

Example:

<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
</head>
<body>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512">
        <style type="text/css">
            /* <![CDATA[ */
            .some_styles {}
            /* ]]> */
        </style>
        <!-- SVG content here -->
    </svg>
</body>
</html>

I imagine there could be issues like the CSS child combinator being misinterpreted as an XML closing bracket, and I have read various posts from people advising using commented out CDATA around inline SVG styles 1 2. However, to my surprise I found that even with CDATA removed and the child combinator being used, my HTML validated. In addition to this, I was unable to detect any problems with the rendering of the SVG in any modern browser.

Here's what has been discussed on SE about including CDATA within a <script> tag, but that's not the same thing as <svg>, so it seemed this warranted its own question.

I don't mind including it, and doing so doesn't cause any trouble. I just wonder if I'm doing the right thing or something unnecessary.


Solution

  • In theory CDATA blocks are required anywhere you'd want to write unescaped text. In XML, only 2 characters need escaping: < and & and both characters are meaningless in CSS.

    That means you don't need CDATA blocks for CSS.

    (Also, you don't need CDATA in HTML because HTML is not XML).

    Edit

    As pointed out in the comments, now that CSS finally supports nesting, ampersand (&) has become the nesting selector. Take that into consideration when writing your CSS within XML files (including SVG).