CSS Reference ยท Units and Values
URL values
Reference for CSS URL values: the url() notation, quoting rules, how relative paths resolve, fragment references and the properties that accept URLs.
A URL value points CSS at an external resource: an image, a font file, a cursor graphic, another stylesheet or a fragment inside an SVG file. It is written with the url() notation around the address, with or without quotes.
Most of the time a URL value is just a path to an image, but it appears in more places than that, and the rules for how a relative path is resolved catch many people out.
.hero { background-image: url("/images/hero.jpg"); } @font-face { font-family: "Brand"; src: url("/fonts/brand.woff2") format("woff2"); }
Try it
Syntax
<url> = url( <string> <url-modifier>* ) | url( <url-token> )
The quoted form is a function containing a string. The unquoted form is a special token that cannot contain spaces, quotes, parentheses or control characters unless they are escaped with a backslash.
Values
| Form | Description |
|---|---|
url("a.png") |
Quoted string. Always safe, even with spaces or parentheses in the name. |
url(a.png) |
Unquoted. Fine for simple paths; characters such as spaces and ) must be escaped. |
url(data:...) |
A data: URL embeds the file in the CSS. Good for tiny images, bad for large ones. |
url(#id) |
A fragment reference, used for SVG elements such as filters, clip paths and masks. |
Usage notes
- Relative paths are relative to the stylesheet, not the HTML page. For an external stylesheet at
/css/site.css,url(img/bg.png)means/css/img/bg.png. In a<style>element or a style attribute it is relative to the document. - Root-relative paths are easiest to reason about.
url("/images/bg.png")always starts at the site root. - A broken URL fails quietly. The image does not show and no error appears on the page, but a layered fallback (as the last tile above) keeps the design usable. Check the network panel when something is missing.
- Fonts need CORS. A font loaded from a different origin must be served with permissive CORS headers, or the browser refuses to use it.
- Where URLs work.
background-image,border-image-source,list-style-image,content,cursor,mask-image,@font-facesrc,@import, and thefilterproperty when pointing at an SVG filter. - Lazy loading. A browser downloads a CSS image only when a matching element is rendered, so unused rules cost nothing.
- Accessibility. Images from CSS carry no alt text. Put meaningful images in HTML.
Browser support
url() is supported everywhere; the extra url-modifier arguments are newer, so check a compatibility table before relying on them.
Related
function-urlโ theurl()function pagebackground-imageโ the most common user@font-faceโ loads fonts by URL- Lesson: Backgrounds