url() and Image Functions
What you'll learn: How to reference external resources with url() and use CSS image functions for adaptive, dynamic images.
What Is url()?
The url() function is CSS's way of linking to external resources like images, fonts, or other files. You've likely seen it in background-image: url('photo.jpg'). Think of it as a file path wrapped in a function—CSS uses it to fetch and display assets.
Basic syntax:
.hero {
background-image: url('images/hero.jpg');
}
Advanced Image Functions
Beyond simple url(), CSS offers functions for adaptive, responsive images:
image()
A more flexible alternative to url() that lets you specify fallbacks and directional hints:
.banner {
background-image: image('hero.webp', 'hero.jpg');
}
If the browser can't load hero.webp, it tries hero.jpg.
image-set()
Lets the browser choose the best image based on screen resolution:
.logo {
background-image: image-set(
url('logo.png') 1x,
url('logo@2x.png') 2x
);
}
On high-DPI screens (like Retina), the browser picks the 2x version automatically.
cross-fade()
Blends two images together with a percentage:
.overlay {
background-image: cross-fade(url('day.jpg'), url('night.jpg'), 50%);
}
Creates a 50/50 mix of both images—useful for transitions or overlays.
Why Use These?
These functions give you CSS-level control over image delivery—no JavaScript needed. You can adapt to device capabilities, reduce bandwidth, and create dynamic visuals directly in your stylesheets.
Key Takeaway: url() links external resources, while image(), image-set(), and cross-fade() provide adaptive, responsive image handling directly in CSS.