The CSS url() function
The CSS url() function points to an external resource by its address, e.g. background: url(hero.jpg). It is used for background images, @font-face files, list markers, masks and SVG references. The path can be quoted or unquoted and is resolved relative to the stylesheet, not the HTML page.
Overview
url() tells CSS where to find an external resource. You will meet it most often as a background image, but it is the same function that loads web fonts in @font-face, points list-style-image at a custom bullet, and references shapes for masks and clip paths.
The detail that catches people out is how the path resolves: it is relative to the stylesheet file, not the HTML document that links it. So url(images/bg.jpg) in a CSS file at /css/site.css looks for /css/images/bg.jpg. Use a leading slash for a root-relative path, or a full URL, when that is not what you want.
The quotes around the path are optional, but quoting is safer when the path contains spaces or unusual characters. For very small assets you can skip the network request entirely with a data: URI, embedding the file's contents directly in the value — great for tiny icons, though it bloats the CSS for anything larger.
Syntax
selector {
background-image: url("images/hero.jpg");
}
@font-face {
font-family: "My Font";
src: url("fonts/myfont.woff2") format("woff2");
}
Example
<style>
.hero {
background: #334155 url("https://picsum.photos/600/200") center / cover no-repeat;
color: #fff;
padding: 44px 20px;
border-radius: 12px;
text-align: center;
font: 700 18px system-ui, sans-serif;
text-shadow: 0 1px 4px rgb(0 0 0 / 0.6);
}
</style>
<div class="hero">background image loaded with url()</div>
Best practices
- Remember paths resolve relative to the stylesheet, not the HTML — use a leading slash for root-relative paths.
- Quote paths that contain spaces or special characters; quoting is harmless even when not required.
- Provide a background-color fallback behind an image so the area is not blank while it loads.
- Consider a
data:URI for very small assets to save a request, but avoid it for large files.
Frequently asked questions
How do I add a background image with url()?
background-image: url("hero.jpg"). The path points to the image file.Is the url() path relative to the CSS or the HTML?
url(img/bg.jpg) is resolved from the stylesheet's location, not the HTML page that links it.Do I need quotes around the URL?
url(a.jpg) and url("a.jpg") both work.Can I use a data URI in url()?
url("data:image/svg+xml,..."). It embeds the asset directly, saving a request — best for tiny files.