Dev.to WebDev 🛠 Dev 👁 2 📖 5 min read

How to find broken URLs in your CSS: fonts, background images and @import that HTML link checkers never see

Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com If your link checker only looks at HTML, it will give a clean report to a site whose typography is a 404, whose hero is a

Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com

If your link checker only looks at HTML, it will give a clean report to a site whose typography is a 404, whose hero is a missing background image, and whose print stylesheet hasn't resolved in a year. Those URLs live in CSS: url() in background-image, background, @font-face, cursor, filter, content, and in @import.

This is a small extractor and checker you can run over the stylesheets your pages actually load.

Find the stylesheets, then find the URLs

You need both steps. A folder of .css files in the repo is a start, but it will miss CDN stylesheets, compiled bundles whose source is .scss, and CSS inlined in a <style> tag. A practical approach:

  1. Crawl or list your HTML (a sitemap, a rendered preview, or find over the built site).
  2. Collect every link[rel=stylesheet], every @import already in those files, and every inline <style>.
  3. Parse those CSS texts for url(...) and further @import.
  4. Resolve each URL against the stylesheet's own location, not against the page. This is the step people get wrong: a url(../fonts/a.woff2) in /assets/css/app.css is /assets/fonts/a.woff2, not relative to /blog/post/.
import re
import sys
from pathlib import Path
from urllib.parse import urljoin, urlparse

import requests

URL_RE = re.compile(
    r"""@import\s+(?:url\(\s*)?['"]?([^'")\s]+)['"]?\s*\)?"""
    r"""|url\(\s*['"]?([^'")\s]+)['"]?\s*\)""",
    re.I,
)
SKIP_PREFIXES = ("data:", "data:", "#")

def extract(css, base):
    found = []
    for m in URL_RE.finditer(css):
        raw = m.group(1) or m.group(2)
        if not raw or raw.startswith("data:") or raw.startswith("#"):
            continue
        found.append(urljoin(base, raw))
    return found

def check(url):
    try:
        r = requests.get(url, timeout=15, stream=True)
        r.close()
        return r.status_code
    except requests.RequestException as e:
        return type(e).__name__

if __name__ == "__main__":
    # args: <css file or URL> <base URL the file is served from>
    src, base = sys.argv[1], sys.argv[2]
    if urlparse(src).scheme in ("http", "https"):
        css = requests.get(src, timeout=15).text
        base = src
    else:
        css = Path(src).read_text(errors="replace")
    for url in sorted(set(extract(css, base))):
        status = check(url)
        flag = "OK" if status == 200 else "FAIL"
        print(f"{flag}\t{status}\t{url}")

For a built static site you can walk dist/**/*.css and pass each file's eventual public URL as the base (for example https://example.com/assets/app.css). In CI, run it against the preview origin so you don't need production to be updated first.

What you will find

Fonts. After a folder move or a hashed-filename build, url(../fonts/Inter.woff2) is the most common miss. Browsers then silently fall back, so nobody files a ticket; the site just looks slightly wrong. Check woff2 and woff if you list both.

Background images. Heroes, icons, and one-off illustrations that were never <img> tags. They also vanish "politely".

@import. An old typography stylesheet on a CDN, or a print.css that nobody has opened. @import is recursive: the imported file has its own url()s, relative to its location. Follow one level at least.

Cache-busted paths that didn't get updated. url(/assets/hero.jpg?v=3) while only hero.jpg?v=4 was deployed. Some servers ignore the query string; some don't.

Absolute URLs to a staging bucket left in a stylesheet after a design handoff.

Skip data: URIs and url(#fragment) references to SVG filters or clip paths inside the same document; they are not network requests.

Relative to the CSS file, not the HTML

This is worth repeating because it produces both false positives and false negatives. If you resolve url(img/x.png) against the page URL, you will check the wrong place and either fail a good site or pass a broken one. Always resolve against the stylesheet URL. For inline <style> on a page, the base is the page URL, which matches how browsers work.

Preprocessor gotcha: in Sass, url() might be left as-is or rewritten depending on the bundler. Run the checker on the built CSS the browser will fetch, not on the .scss source, or you will check paths the compiler was supposed to change.

A site can have a clean HTML link report and still be missing its fonts and hero images, because those URLs never appear as href or src. linkbruno.com is at its best when the check includes the assets your pages load, not only the links between pages — and stylesheets are one of the places those assets hide.

Sourcemaps and hashed filenames

Production CSS often looks like app.3f2a1c.css with font files named inter.7aa91b.woff2. That is fine when the HTML and the CSS are built together. It is not fine when a long-lived HTML page (or a cached email, or a third-party widget) still points at last week's stylesheet, which still points at last week's fonts, which you just deleted to "clean up the bucket".

If you hash filenames, keep previous assets around for a while, or keep the unhashed aliases as redirects. The CSS checker will tell you about the current build; it will not tell you about last week's HTML unless you also crawl the live site, not only the new artifact.

Hook it to the same CI as HTML checks

Fail the build if a url() on your own host 404s. Third-party font CDNs can be warn-only if you don't want a Typekit blip to block a release, but then run a scheduled check in production, because "it worked at build time" will not help when the CDN path is retired a month later.

A useful extra assertion: every @font-face source on your own origin returns 200 and a content-type that looks like a font. A 200 with text/html is usually a SPA fallback or a custom 404 page, and the browser will not treat it as a font.

Related reading

Has a "the site looks off" ticket ever turned out to be a 404 on a font or a background image? Did your link checker see it, or only a human?

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.