π What is the url() Function?
The url() CSS function is used to load external resources such asimages, fonts, videos, cursors, and SVG files directly in your styles. Itβs one of the core building blocks in CSS for linking external assets.
Note
β Accepts absolute, relative, and data URLs
β Can include quotes or be unquoted
π― Why Use url()?
- To load background images
- To include custom fonts (via @font-face)
- To add list-style images
- To change the mouse pointer (cursor)
- To embed SVGs and patterns
π Syntax
url() Syntax
url(<path-to-resource>)You can use quotes or omit them:
Quoted & Unquoted
url('image.png')
url("image.png")
url(image.png)πΌοΈ Example 1 β Background Image
Background Image
.banner {
background-image: url('images/hero.jpg');
background-size: cover;
}πͺͺ Example 2 β @font-face with url()
Loading Custom Fonts
@font-face {
font-family: 'MyFont';
src: url('/fonts/myfont.woff2') format('woff2');
}
body {
font-family: 'MyFont';
}url() is essential for importing custom fonts locally.
π§΅ Example 3 β SVG Icons with url()
SVG Background Icon
.icon {
background: url('icons/user.svg') no-repeat center;
width: 24px;
height: 24px;
}SVGs scale perfectly at any resolution β great for modern UIs.
π±οΈ Example 4 β Custom Mouse Cursor
Cursor Example
button {
cursor: url('cursor.cur'), pointer;
}If the custom cursor fails, CSS falls back to pointer.
π Example 5 β List Style Image
List Image
ul {
list-style-image: url('check.svg');
}π¨ Example 6 β Mask Images
Mask Example
.mask {
mask-image: url('shapes/circle.png');
}Masks allow advanced clipping and reveal effects.
π Relative vs Absolute Paths
| Type | Example | Meaning |
|---|---|---|
| Relative Path | url('../assets/bg.jpg') | Relative to the CSS file |
| Absolute Path | url('/images/logo.png') | Starts from website root |
| Full URL | url('https://example.com/bg.png') | Loads from external site |
Note
π§ͺ Data URLs (Inline Images)
You can embed an entire image directly inside CSS using data URLs.
Data URL Example
.logo {
background-image: url('data:image/svg+xml,<svg>...</svg>');
}Note
β οΈ But increases CSS file size
π― Using url() with CSS Variables
Dynamic URLs
:root {
--bg: url('light.jpg');
}
.dark {
--bg: url('dark.jpg');
}
.banner {
background-image: var(--bg);
}Great for theme switching or dynamic UIs.
β οΈ Common Mistakes
- β Incorrect relative paths (most common error)
- β Using url("") with spaces or unescaped characters
- β Expecting url() to load blocked remote resources (CORS errors)
- β Confusing CSS path resolution with HTML path resolution
Note
π₯ Summary
The url() function is one of CSSβs most essential tools for linking external resources. Whether you're loading images, fonts, cursors, or SVGs, url() makes styles richer, more visual, and more interactive.
Learn more βMDN Docs π