CSS url()

By

Learn how the CSS url() function loads resources like background images, using relative paths, root-relative paths, and absolute URLs to external files.

~~~

The url() function is how CSS points to an external resource: a background image, a font file, a custom cursor, or another stylesheet loaded with @import.

The most common use is loading a background image:

div {
  background-image: url(test.png);
}

In this case I used a relative URL, which searches the file in the folder where the CSS file is defined.

I could go one level back

div {
  background-image: url(../test.png);
}

or go into a folder

div {
  background-image: url(subfolder/test.png);
}

Or I could load a file starting from the root of the domain where the CSS is hosted:

div {
  background-image: url(/test.png);
}

Or I could use an absolute URL to load an external resource:

div {
  background-image: url(https://mysite.com/test.png);
}

Where else can you use it?

url() shows up in more places than backgrounds. You’ll find it in @font-face rules to load font files, in cursor to set a custom cursor, and in list-style-image to replace list bullets:

@font-face {
  font-family: 'Inter';
  src: url(/fonts/inter.woff2) format('woff2');
}

li {
  list-style-image: url(/icons/arrow.svg);
}

The syntax is the same everywhere. What changes is the property using it.

Quotes or no quotes?

Quotes are optional. These three lines are equivalent:

background-image: url(test.png);
background-image: url('test.png');
background-image: url("test.png");

Quotes become required when the URL contains characters that would confuse the parser, like spaces or parentheses. My advice is to add them when in doubt, since they never hurt.

Watch out: paths are relative to the CSS file

Here’s the thing that trips people up. A relative path inside url() resolves from the location of the CSS file, not from the HTML page that loads it.

Say your stylesheet lives at /css/style.css and it contains url(header.png). The browser requests /css/header.png. It doesn’t matter if the page using that stylesheet is at /blog/post.html.

This bites when you reorganize a project. You move the stylesheet into a subfolder, and every image it references breaks, even though the HTML pages didn’t change.

The fix is to use root-relative paths like url(/images/header.png). Those always resolve from the domain root, so they keep working no matter where the CSS file lives.

If a resource fails to load, the rule doesn’t crash anything. The element just renders without its background, and you’ll see a 404 in the network panel of the browser devtools. That’s the first place to check when a background image doesn’t show up.

Tagged: CSS · All topics
~~~

Related posts about css: