CSS — Files You Serve
A backend developer rarely writes much CSS, but you will be asked why "the site looks broken" after a deploy. The HTML arrives, the text is there, and everything is plain black on white. Nine times out of ten the stylesheet never reached the browser, and that part is the backend's job.
The rule
CSS runs in the browser; the server only delivers the file.
CSS is a set of rules that say how elements should look:
.book-card {
border: 1px solid #ddd;
padding: 1rem;
}The HTML points at it:
<link rel="stylesheet" href="/static/site.css">When the browser meets that tag, it makes a separate GET /static/site.css. From the server's point of view, CSS is a static file: it does not change per user and no code runs to make it. Serving it well comes down to three things:
- The right path: the file must exist at the URL the HTML names. A 404 here gives you an unstyled page.
- The right type: the response must say
Content-Type: text/css. Browsers can refuse a stylesheet sent with the wrong type. - Sensible caching: CSS rarely changes, so browsers should keep a copy instead of downloading it on every page.
Caching creates a problem: if a browser keeps site.css for a month, how does it see tomorrow's change? The usual answer is a content hash in the file name. The build step produces site.3f9a1c.css; when the file changes, its name changes to something like site.b72e05.css, and the HTML points at the new name.
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: public, max-age=31536000, immutableA hashed file can be cached for a year, because any new version is a different URL.