Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I escape image URLs for CSS?

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?

like image 456
bts Avatar asked Sep 01 '14 22:09

bts


2 Answers

const style = "background-image: url(\"" + CSS.escape(imageUrl) + "\")";

See https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape

It is an experimental new thing, but it seems to be quite well supported (as of 2021).

like image 91
Josef Kufner Avatar answered Oct 13 '22 09:10

Josef Kufner


If you are setting the background url through JS, then the correct and safe ways is using encodeURI() and wrapping in quotes.

node.style.backgroundImage = 'url("' + encodeURI(url) + '")';
like image 33
Mārtiņš Briedis Avatar answered Oct 13 '22 09:10

Mārtiņš Briedis