How should I escape image URLs for CSS?

Tags: css,url,escaping,xss

Problem :

I have a div which will receive a CSS background image from user chosen URL, like so:

background-image: url("/* user specified URL here*/")

How should I escape the URL so that it's safe to embed in the CSS? Is escaping the quotes enough?

Solution :

Is escaping the quotes enough?

No, you also should worry about backslashes and newlines.

Here is the CSS grammar for a double quoted URI:


where {nl} is


and {escape} is a backslash-escaped character. So a trailing backslash will break your CSS. A non-escaped newline likewise.

I would strongly recommend to remove all whitespace and finally escape " and \

    CSS Howto..

    How to move a span to a different position in a DIV

    How to make div to expand vertically without using overflow or javascript or hardcoded values such as margins

    How to make a conjoined input with flexible width

    css boxes are not shown in the right place (when adding doctype)

    How SCSS rule evaluation done by browser

    How do I get a jquery function to only affect the child element of 'this'

    css + how to have cells with a border and cells without a border

    how to not inherit? or how to reset inherited width to the value before? (css)

    How to locate a pointed div element in css

    How can my css div with the display flex property be alignd to the right when it's wrapping?

    Extjs: how Element's up/down functions work?

    How to stick a div when scrolled past 50% of the item?

    How can I create an overlay that stays in DOM as opacity 0 but doesn't prevent content from being clickable?

    How to make a background header image extend to full width of browser

    How to fix smooth text in IE?

    How do you set the filepath for css in hiccup with Clojure using the html5 tag?

    How to fix error from posting html element and prevent it from running

    How to move links in the middle of the Web page using html/css?

    how to add style to form under echo statement by css [closed]

    how to display tabs in more than one row having the extra tabs coming one row up rather than one row below?

    web app CSS navbar retina icons - How can I fit a 60x60 icon into a 30x30 background-image on IE7+8?

    tooltip box not showing using css

    CSS animations - How to toggle direction with one keyframes declaration

    How can I organize my css rules?

    Nested CSS: How to get to the child?

    How to change CSS portrait to landscape in iphone?

    How can I vertically centre bullets that bracket headers

    How can I float right two span tags on different lines?

    How to display a div at the center of viewport?

    Show popup after page load