LilligantEX LilligantEX - 1 month ago 10
CSS Question

Can You Style a Broken Link With CSS?

Is it possible to style a broken link (ie. one that tries to link to a non-existent page on your site) in a different colour? eg. working links are blue, broken links are red?

Or, if not CSS, is it possible to identify them through JavaScript and then style them later? (jQuery is not available to me.)

Answer

No, you cannot style a broken link with CSS. The browser does not know if a link is broken until some agent tries to access the link.

You could conceivably write some Javascript that would attempt to fetch every page for every link in your document and then, upon failure of some of the links, it could dynamically change the style of the link to something else. But, this is likely a very bad idea because it would potentially waste a lot of bandwidth and waste some CPU (both particularly important on mobile).

And, even further is some of the links are to other domains, the browser will likely prohibit your Javascript from directly fetching those pages (same-origin security restrictions) so you may not even be able to do it with Javascript.

A scalable system that could work would be the have your server check the links you're using in your pages on some interval (perhaps once every few days), keep that info in a local database and then you can add a class to a link (server-side) when rendering the page and then a CSS rule can style that link differently. Plus, the server is not subject to same-origin restrictions so you don't have that limitation doing it server-side. There are lots of gotchas when determining off-line that you will have to watch out for because a host can be down temporarily, can be down only from a particular route on the internet, etc...