8-Bit Nostalgia Meets Modern CSS: My ZX Spectrum Blog Theme
8-Bit Nostalgia Meets Modern CSS: My ZX Spectrum Blog ThemeHow I built this blog’s ZX Spectrum theme with modern CSS: cassette-loading stripes, a Dizzy cursor, favicon caching, and progressive enhancement.
A couple of months ago, I decided my blog needed a little more personality than the usual light and dark themes. I started experimenting with themes inspired by early monochrome computer terminals, beginning with the familiar green-on-black display, reminiscent of the command line I spend far too much time staring at as a web developer. That was soon followed by an amber variation, once common in computing, finance, and industrial systems, and perhaps more recognisable today from the Pip-Boy interface in Fallout. They looked good, I love their simplicity, but they're hardly groundbreaking.
Then, during a conversation with my youngest son about the computer games I played growing up, inspiration struck. Why not create themes inspired by retro computers and gaming? I started with the distinctive green display of the Nintendo Game Boy, followed by the Commodore 64, then the unmistakable blue of IBM PC DOS, and finally the classic Apple Macintosh. Before long, my blog was starting to resemble a retro gaming arcade, thankfully without the need for a pocketful of coins to keep playing!
Shortly after adding these themes, while rummaging through some old boxes in the garage, I stumbled across a real treasure trove of nostalgia: a box of original ZX Spectrum games from my childhood! The memories came flooding back. The hard plastic keyboard, colourful loading screens, and the unmistakable screech of games loading from cassette tapes. Looking back, the ZX Spectrum was a big part of my childhood and arguably helped inspire my career in software development. How on earth had I overlooked it? Probably something to do with my age, although I'd rather not dwell on that! 😭
There was only one thing for it, my blog needed a ZX Spectrum theme.
What is a ZX Spectrum?
The ZX Spectrum, developed by Sir Clive Sinclair's Sinclair Research, was my very first gaming computer. While my friends had the luxury of an Amiga or a Mega Drive (Genesis), I had my trusty Spectrum, which loaded games using good, old-fashioned cassette tapes.
Now, you might be wondering why I'm mentioning how these computers loaded their games. Well, while the Amiga used 3.5-inch floppy disks and the Mega Drive used ROM cartridges, my beloved Spectrum required something rather more precious: patience. Lots and lots of patience!
I owned a ZX Spectrum +2, which came with a built-in cassette player. So, while my friends were already happily playing their games, I was still waiting for mine to load. And this wasn't a quiet process either. Oh, no. The Spectrum practically screamed at you through the television while it loaded. If you've never experienced this delightful noise, here's an example of a Spectrum loading a game on YouTube. You're welcome.
You may be asking, "Why not just turn the volume down?" Well, you could, but then you risked missing the crucial moment when you needed to turn the cassette over or, worse still, swap it for another one. Take too long, and there was a good chance you'd just wasted ten minutes of your life waiting for a game that would never load.
And when I say fail to load, I mean exactly, that. You’d hear that unmistakable click of the cassette player stopping, look up at the television with a brief moment of hope, only to find yourself staring at a blank screen surrounded by colourful stripes. No error message, no helpful explanation. Just the crushing realisation that you’d wasted another ten minutes of your life and would have to start the whole process again. Wonderful.
Looking back, the Spectrum really was an exercise in patience. Every game involved five to ten minutes of sitting there, hoping that this time, just maybe, it would actually work.
I vividly remember having a copy of Altered Beast that I only ever managed to get to load once. Every other attempt ended in failure. I distinctly remember thinking it was quite a good game, too. At least, based on the one occasion I actually got to play it!
And yet, despite all that frustration, I absolutely adored my Spectrum.
For readers wondering what a ZX Spectrum +2 looked like, here it is in all its glory!

ZX Spectrum +2 Specifications
You would not believe the nostalgia that came over me when listening to that YouTube video of a game loading earlier in the post. It was like I was 8-years old, back before the internet, and UK TV only had 4 channels! Even though compared to today's standards, the graphics look truly terrible, the gameplay of some of the games was simply fantastic. Considering game developers had very limited resources to work with:
- Typical loading speed: 1,500 bits per second
- Typical cassette storage: 100–300 KB depending on length of the cassette e.g. 7.5 mins to 45 mins
- Total RAM: 128 KB
- CPU speed: 3.5 MHz
Yes, you are reading that right, the ZX Spectrum +2 had just 128 KB of RAM and a 3.5 MHz processor. To put that into perspective, a modern smartphone with 8 GB of RAM has over 65,000 times more memory, while its processor runs at a clock speed roughly 1,000 times faster. And yet, somehow, we managed to play entire games on it, complete with graphics, sound, and hours of entertainment! As of the time of writing, you may have heard whispers of a small, relatively unknown indie game called Grand Theft Auto VI. Apparently, it's generating a little excitement, despite its rather modest 212 GB download size. That's roughly 1.7 million times more data than the ZX Spectrum +2 had RAM. To put that into perspective, you'd need around 1.4 million cassette sides, each holding 150 KB, just to store the game. I suspect even the most patient Spectrum enthusiast might struggle with that loading time!
The incredible part about this time in the gaming industry was how quickly the technology was evolving, and the hoops that game developers needed to jump through to get an edge on their competition. For example, the ZX Spectrum could only display two colours within any 8×8 pixel block, resulting in something known as attribute clash, where moving characters would unexpectedly change colour as they crossed different backgrounds. Developers found ingenious ways around this, including using monochrome graphics, carefully positioning sprites, and designing levels around the hardware's limitations.
Then there was memory. With just 48 KB available on earlier Spectrum models, developers had to squeeze entire games, including graphics, sound, and gameplay logic, into less memory than a typical image on a modern website. They achieved this by reusing graphical assets, compressing data, and writing highly optimised Z80 assembly language. There were no modern game engines or powerful graphics processors to help out, just incredibly talented developers squeezing every last bit of performance out of the hardware available.
Just to put things into perspective, the image of the ZX Spectrum +2 I included above is 54 KB. Let that sink in for a moment! A single image on this blog post is larger than the entire 48 KB of RAM available on the original 48K ZX Spectrum. Developers somehow managed to squeeze entire playable worlds into that tiny amount of memory, including the game logic, graphics, sound, animations, and everything else needed to make them work! And here I am, decades later, optimising the file size of a single image of the very machine they achieved all of this on!
I genuinely find it mind-boggling. The sheer ingenuity, creativity, and technical skill of those developers, working within such incredibly restrictive hardware limitations, is nothing short of astonishing. It gives me an enormous appreciation for the games I spent so many hours playing as a child.
ZX Spectrum Games I Played
So, let’s discuss the games I used to play. Or, more accurately, the games I occasionally played when the cassette player decided to cooperate and actually load them.
As mentioned earlier, successfully loading a game was often just as challenging as playing the game itself!
Elite (1985)

Now, I know what you may think, what on earth is in the screenshot above? Well, it’s actually one of the greatest space shooters in gaming history, it was created by legendary programmers David Braben and Ian Bell at Cambridge University when they were students in their early twenties. It was originally written for the BBC Micro in 1984, but was ported to the Spectrum in 1985. Remember when I mentioned the constraints on programmers earlier in the post? Well, David and Ian were the pioneers in building a gigantic game and fitting it into an incredibly small file size.
Here are just a few incredible facts about the game and how it was years ahead of other space games:
- 22 KB of code: The original BBC Micro game packed an entire 3D universe, combat, trading, AI, and navigation into approximately 22 KB of machine code, for context the screenshot image above is 40 KB!
- 2,048 star systems: Eight galaxies containing 256-star systems each, all available to explore.
- Procedural generation: Thousands of planets were generated mathematically rather than individually stored in memory.
- Pioneering open-world gameplay: Players could become traders, pirates, bounty hunters, or explorers, with no prescribed route through the game.
- Real-time 3D graphics: Fully rotating, moving 3D spacecraft rendered on an 8-bit computer without a dedicated graphics processor.
- Hidden-line removal: An advanced rendering technique prevented invisible edges of 3D objects from appearing on-screen.
- Assembly language: Written predominantly in low-level machine-specific assembly code to maximise performance and minimise memory usage.
- Procedural descriptions: Planetary descriptions were algorithmically generated rather than stored as individual paragraphs.
- Interstellar economy: Hundreds of planetary economies supported trading, commodity prices, smuggling, and profit-making.
- Artificial intelligence: Enemy spacecraft could independently navigate, pursue, attack, and react to the player's actions.
- 3D space station docking: Players had to manually align their spacecraft with rotating space stations or risk a collision.
- Persistent progression: Players earned credits, upgraded spacecraft, improved equipment, and built their reputation over time.
- Preserved source code: The original BBC Micro assembly code is available to explore through the Elite on the 6502 project.
I spent countless hours exploring the game’s many star systems before returning to Lave, the planet where you began the game, desperately trying to dock at Lave Station to sell my hard-earned bounty. Having survived countless encounters with hostile spacecraft, it was embarrassing how often my journey ended with me crashing into the very space station I was trying to dock with!
Dizzy: The Ultimate Cartoon Adventure (1987)

It’s time to introduce you to my favourite Spectrum game franchise, Dizzy! It was created by the incredible Oliver Twins (Philip and Andrew). They have an impressive CV of games, dating all the way back to 1983 with a game called Road Runner, for a platform I’ve never heard of until writing this post, Dragon 32. TIL!
Dizzy is the main character of the franchise, a little egg with red boxing gloves and boots who runs, jumps, and somersaults around a colourful fantasy world. As mentioned, the creators brothers Philip and Andrew Oliver were just 19 when the game was released in 1987. The objective was to explore the land of Katmandu, collect four magical ingredients, and create a potion to defeat the evil wizard Zaks. Originally released for just £1.99 (approximately £7.30 adjusted for inflation), it was an absolute bargain for hours of entertainment, frustration, and the occasional temptation to throw your Spectrum across the room! Dizzy went on to become one of Britain's most recognisable video game characters. Interestingly, his egg-shaped appearance came from the fact that a rounded character was easier to animate, while his name was inspired by his rather dizzying somersaults!
I remember spending countless hours wandering between screens, collecting objects, searching for clues, and desperately trying to work out which item solved which puzzle. You could only carry one item at a time, and with no internet walkthroughs, autosaves, or helpful hints, you were largely on your own! I'd occasionally experience a moment of absolute bliss after solving a puzzle, only to mistime a jump, lose my final life, and find myself right back at the beginning. Three lives, no saves, and hours of progress lost! Yet, for some reason, I'd happily start all over again!
Treasure Island Dizzy (1988)

Another fantastic game from the Dizzy franchise, released just a year after Dizzy: The Ultimate Cartoon Adventure (1987). This time, my favourite egg-shaped adventurer found himself shipwrecked on a mysterious island, tasked with finding his way home. The sequel introduced several improvements, including smoother animations, the ability to carry three items instead of just one, and underwater exploration using a snorkel. There were also 30 hidden gold coins to collect, many cleverly concealed within the scenery. Unfortunately, Dizzy also had just one life, meaning a single mistake sent you straight back to the beginning. As if these games weren't frustrating enough already!
One of my fondest memories was exploring the elaborate treehouse village, reportedly inspired by the Ewok village from Star Wars: Return of the Jedi. I distinctly remember climbing through what felt like an endless maze of trees before reaching an interesting-looking platform. Naturally, instead of progressing through the game, I decided to jump off it, watching Dizzy somersault through several completely empty screens (in the sky) before eventually landing back on top of a palm tree, that you can see in the screenshot above. I have absolutely no idea why I found this so entertaining, but it's one of those strangely specific childhood memories that's stayed with me for nearly 40 years!
New Zealand Story (1989)

It's remarkable how much you forget about a game until you revisit it more than 30 years later! Originally developed by Japanese gaming company Taito in 1988, The New Zealand Story arrived on the ZX Spectrum in 1989, published by Ocean Software and programmed by Gerald Weatherup, with music adapted by Jonathan Dunn. You played as Tiki, a rather adorable little kiwi bird armed with a bow and arrows, on a mission to rescue his friends from an evil seal called Wally. The game featured colourful, sprawling levels, flying platforms, and all sorts of strange enemies determined to ruin your day.
But there's one particular memory that's stuck with me all these years, and it's not a particularly pleasant one! Each level had a hidden time limit, and if you spent too long exploring, a warning would appear before an invincible little red devil arrived to chase you down and kill you instantly. No negotiating, no second chances, just sheer panic as you desperately tried to reach the exit! Looking back, I suspect this is precisely why I have absolutely no patience for games with time limits as an adult. Forget childhood nostalgia, The New Zealand Story scarred me for life!
Fantasy World Dizzy (1989)

I suspect you've spotted a pattern by now. I was, and still am, a big fan of Dizzy! Released in 1989 by Codemasters, Fantasy World Dizzy was the third adventure created by Philip and Andrew Oliver, and it felt like a significant step forward for the series. The graphics were more colourful and detailed, the inventory system had been improved, and, for the first time, we were introduced to the Yolkfolk, including Daisy, Denzil, Dylan, Dozy, and Grand Dizzy. Rather than simply collecting objects and solving puzzles, you now had characters to interact with and a proper story involving rescuing Daisy from the clutches of the evil King Troll. I secretly wished I could play as one of the other characters! Remarkably, the Oliver Twins squeezed all 50 screens of the game into just 34 KB, less than the 38 KB screenshot of the game above!
One particular memory that has stayed with me is the crocodile lurking in the water outside the castle. To escape and explore the wider world, you had to jump onto its nose and then time your next jump perfectly to avoid becoming its lunch! I distinctly remember Dizzy somersaulting through the air, landing precariously on the creature, and desperately trying to jump away before being eaten. It was one of those ridiculously simple obstacles that could become unbelievably frustrating, particularly when you mistimed a jump and had to try again. Looking back, it's incredible how something as mundane as jumping over a crocodile could provide so many hours of entertainment!
Sim City (1990)

SimCity was originally developed for the Commodore 64 in 1985, before eventually making its way to the ZX Spectrum in 1990. I spent a fair amount of time playing it on my trusty Spectrum +2, building roads, adding residential and industrial zones, and generally attempting to create a thriving city, usually with questionable results! It was quite different from the other games I was used to playing, with no real ending or traditional way to win. Instead, you could keep expanding, experimenting, and watching your city develop, which probably explains why I became such a massive fan of the later games in the series.
Unfortunately, there was one rather significant drawback with the game (for me at least). My Spectrum +2 relied on cassette tapes, and saving your carefully constructed city wasn’t straightforward, unlike the Spectrum +3, which featured a floppy disk drive. I remember spending ages getting the game to load (when it felt like cooperating!), only to spend hours building a city that would disappear the moment I switched the computer off. Every session meant starting again from scratch, which rather took the shine off things. Still, it didn’t stop me coming back for more, and thankfully, later versions on other platforms meant I could finally build a city without having to demolish it every time I wanted to turn the computer off!
Magicland Dizzy (1990)

Now, I know what you must be thinking: “Dizzy, again!?” Yes, I promise this is the last one! Magicland Dizzy, released on the ZX Spectrum in 1990, was another adventure involving the evil wizard Zaks, who had scattered the Yolkfolk across a magical world, casting various spells on them. I remember wandering around collecting objects, trying to work out which seemingly unrelated items belonged together, and occasionally stumbling across a solution more through luck than judgement! There were plenty of familiar frustrations too, particularly trying to land Dizzy’s somersaults without accidentally sending him tumbling into something unpleasant.
One puzzle that has stuck with me all these years involved waking up Dozy, the permanently sleepy member of the Yolkfolk, who was lying on an altar under a magical sleeping spell (as seen in the screenshot). If my memory serves me correctly, I had to use some sort of metal crucifix and lightning to wake him up. Well, it turns out I wasn’t entirely wrong! You actually needed a lightning rod and a genie summoned from an ancient lamp to deliver an electrical shock and wake him. It sounds rather extreme, particularly when a gentle shake might have worked, but this was the 90s, and apparently giving your friends an electric shock was considered a perfectly reasonable way to wake them up!
Hero Quest (1991)

Like any respectable computer-obsessed boy growing up in the late 80s and early 90s, my interests extended beyond computers to Games Workshop. I was particularly fond of Warhammer 40,000 (40K), especially the Space Marines and Terminators, but I also owned the HeroQuest board game. So, when Gremlin Graphics released the ZX Spectrum adaptation in 1991, I couldn't resist. The game faithfully recreated the tabletop experience, allowing you to explore dungeons as a Barbarian, Dwarf, Elf, or Wizard, searching for treasure, discovering secret passages, and battling orcs, goblins, and other unpleasant creatures. I remember spending hours cautiously exploring the isometric dungeons, opening doors without knowing what horrors awaited on the other side, and desperately hoping the virtual dice would be kinder than their physical counterparts! It was one of those games I genuinely enjoyed playing both on my own and with friends, assuming, of course, that my trusty Spectrum had successfully loaded it in the first place!
One thing I absolutely loved, though, was the incredible cover artwork. The muscular Barbarian charging into battle, sword raised above his head, surrounded by fantastical creatures, was everything a young Warhammer enthusiast could possibly want. The dramatic fantasy illustration was the work of artist Les Edwards, and it genuinely felt like something you could spend hours examining, discovering little details you hadn't noticed before. Of course, the actual Spectrum graphics were somewhat less spectacular, but that hardly mattered. The artwork had already done its job, convincing my imagination that those colourful little pixels represented an epic adventure!
Why I Built a ZX Spectrum Theme
So, other than taking you on a rather unnecessary trip down memory lane, what exactly is the point of this blog post? A perfectly reasonable question, and one I was beginning to ask myself. The original intention was to write about the browser technologies, CSS techniques, and various bits of frontend wizardry involved in creating my new ZX Spectrum-inspired theme. Unfortunately, somewhere between reminiscing about cassette tapes that refused to load, Dizzy repeatedly falling to his death, and countless hours spent staring at eight-bit graphics, I appear to have wandered slightly off-topic.
Several hundred words later, I’ve essentially written a love letter to a computer that spent a considerable amount of its time testing my patience. Anyway, before I start discussing the merits of rewinding cassette tapes with a pencil, let’s return to the original purpose of this post and explore how I brought a little piece of 1980s computing into a modern web browser. Thankfully, without having to wait ten minutes for anything to load. Although, given the state of some modern websites, perhaps we haven’t made quite as much progress as we’d like to think!
Browser Technologies Behind the ZX Spectrum Theme
Enough childhood nostalgia! Let’s explore the modern browser technologies I’ve used to bring the Spectrum theme to life. If you haven’t tried it yet, click the little computer icon in the right of the navigation and look under the “Retro” section. Suggestions for other retro themes are always welcome, just let me know!
Paper and Ink: Recreating the ZX Spectrum
Before going any further, it’s worth explaining what PAPER and INK actually meant on the ZX Spectrum. Unlike modern computers, where individual pixels can display practically any colour, the Spectrum used INK to define the foreground colour (text and graphics) and PAPER for the background. Simple enough, although there were some rather frustrating limitations to how these colours could be used, which I'll cover shortly. Thankfully, none of these limitations apply to the website theme, but I thought these concepts were worth mentioning for a little historical context before we get into how the Spectrum handled colours.
As touched on above, one of the most recognisable characteristics of the ZX Spectrum was its very limited colour palette. The hardware supported just 8 base colours, with 7 available in both normal (dark) and bright variants. Black remained black regardless of the brightness setting, giving developers a grand total of 15 colours to work with!
For this theme, I've recreated the Spectrum's original palette using the following hexadecimal colour values:
- Black (#000000)
- Dark blue (#0000D7)
- Bright blue (#0000FF)
- Dark red (#D70000)
- Bright red (#FF0000)
- Dark magenta (#D700D7)
- Bright magenta (#FF00FF)
- Dark green (#00D700)
- Bright green (#00FF00)
- Dark cyan (#00D7D7)
- Bright cyan (#00FFFF)
- Dark yellow (#D7D700)
- Bright yellow (#FFFF00)
- Light grey (#D8D8D8)
- Bright white (#FFFFFF)
Compare that to a modern browser supporting 16.7 million colours, and it's remarkable just how much time, effort, and ingenuity developers put into making games look respectable with so little to work with!
Interestingly, these hexadecimal values are modern approximations rather than definitive representations of the original Spectrum colours. Their appearance varied depending on the television being used, and the fact that the hardware didn't work with hexadecimal colour values in the way modern browsers do.
While some of the brighter colours have direct equivalents among the 148 named CSS colours, including blue, red, magenta (fuchsia), cyan (aqua), yellow, and white. The darker Spectrum colours don't have exact named equivalents, so hexadecimal values provide a more consistent way of recreating the Spectrum colour palette.
And yes, despite supporting 148 named colours, the CSS specification still insists on spelling "colour" as "color". Apparently, there wasn't enough room for that extra letter!?
Another interesting limitation was the Spectrum's colour attribute system. Although its max screen resolution was 256 × 192 pixels (yes, really!), colours were assigned in blocks of 8 × 8 pixels. Each block could have just two colours, one for the foreground (INK) and another for the background (PAPER), with a shared brightness setting. This frequently resulted in the infamous attribute clash, where colours appeared to bleed between objects occupying the same block.
The Spectrum's distinctive character grid and visual design heavily inspired this theme, although recreating them didn't require anything as sophisticated as CSS Grid or Flexbox. Instead, the layout continues to use Utopia.fyi, just like the rest of the blog, while the typography uses a users system's default monospaced fonts to recreate that familiar “retro" appearance.
The advantage of using installed system fonts, is it avoids the need for @font-face, eliminating additional font downloads and potential rendering issues such as Flash of Invisible Text (FOIT). Fewer resources to download, less complexity, and a small but worthwhile improvement to both web performance and perceived performance.
The result is a theme inspired by the original hardware rather than a pixel-perfect emulation. It captures the familiar colours, typography, and character-based appearance of the ZX Spectrum while retaining the blog’s existing responsiveness, accessibility, and, as always, my top priority: frontend web performance.
Not bad for recreating the look of a computer that's over 40 years old!
Recreating the Cassette Loading Effect
The ZX Spectrum loading screen was arguably one of the most iconic, and frustrating, experiences of 1980s gaming. As mentioned earlier, loading a game meant enduring 5 to 10 minutes of screeching noises, occasional pauses, and absolutely no guarantee the game would actually load! For those curious enough to relive the experience, have a listen to this YouTube video of the Spectrum loading screen. You'll also notice the distinctive border with its animated, colourful stripes.
I wanted to recreate that familiar effect for the Spectrum theme, and thankfully, modern CSS makes it surprisingly straightforward. No images, additional downloads, or JavaScript required! Just CSS gradients, custom properties, and a little animation (assuming a user agrees to it).
Creating the Border
The first step was to create a border (the bezel) around the page where the loading stripes could appear. Rather than using a traditional CSS border, I used the <html> element's background and added a margin around the <body>:
html[data-theme="spectrum"] body {
margin: var(--ns-spectrum-bezel);
min-block-size: calc(100vh - var(--ns-spectrum-bezel) * 2);
background-color: var(--ns-body-bg);
}The --ns-spectrum-bezel CSS custom property references --space-m, one of the spacing values generated by Utopia.fyi. This creates a consistent gap around all four sides of the page.
The <body> element then covers the middle with the Spectrum's familiar light grey PAPER colour (#d8d8d8), leaving the colourful background of the <html> element visible around the edges only.
The interesting part here is the min-block-size property. In this case, it works similarly to min-height, ensuring the body has a minimum height that fills the available space within the browser viewport. The calculation takes 100vh (which is the full height of the viewport) and subtracts the bezel thickness twice (--ns-spectrum-bezel) to account for the top and bottom margins, thus leaving the perfect PAPER size for the browser window.
The reason I built it this way was to prevent pages with very little content from leaving a large area of loading stripes underneath the main content. Instead, the stripes remain neatly around the edges of the page, just as they did on the original ZX Spectrum, regardless of how big or small your TV was!
Creating the Colourful Stripes
Next came the stripes themselves. As mentioned earlier, rather than creating an image, I used the CSS repeating-linear-gradient() CSS image function, which allows us to generate repeating patterns using nothing more than a few lines of CSS.
The trick is to give each colour two positions, defining exactly where it starts and ends. For example:
var(--ns-spectrum-yellow) 0 2px,
var(--ns-spectrum-blue) 2px 3px,
var(--ns-spectrum-yellow) 3px 7px,In this example, yellow occupies the first 2 pixels, blue takes up the next pixel, and yellow returns for another 4 pixels.
Because each colour starts exactly where the previous one ends, the browser creates sharp edges rather than blending the colours together. This is ideal for recreating those familiar loading stripes.
Incidentally, the same technique is used for the colourful rainbow in the page header, although that uses a single linear-gradient() CSS function with percentage-based colour stops instead.
Repeating and Animating the Stripes
With the colours defined, the next step was to repeat the pattern down the screen.
The CSS defines two repeating gradients, each with a slightly different pattern length:
background-size:
100% 40px,
100% 48px;
background-repeat: repeat;Each gradient spans the full width of the page, with its pattern repeating every 40 or 48 pixels respectively. The bright blue background colour sits behind both gradients.
To recreate the movement of the original loading screen, CSS animations change the background-position of the gradients, using values such as:
background-position:
0 -6px,
0 11px;The negative value moves the first gradient upwards, while the positive value moves the second downwards. By changing these positions at irregular intervals, the stripes appear to jump between different arrangements, much like the original cassette loading screen.
There's one small catch with the current implementation, however. Both gradients use completely opaque colours, meaning the first gradient covers the second entirely. So, although both backgrounds are being animated, only the first is actually visible.
Adding transparent sections to the first gradient would allow the second to show through, creating a more varied effect. For now, though, the visible gradient is enough to recreate the familiar appearance.
And that's really all there is to it. A handful of CSS properties recreates one of the most recognisable parts of the ZX Spectrum experience, without downloading a single image or relying on JavaScript. Now you can sit and watch the ZX Spectrum loading pattern in peace without the stress of waiting to see if the game will load or not! Nostalgic bliss ...
Animation with @keyframes, steps(1)
Next we add a little more advanced animation techniques purely in CSS.
One of the things I remember most about loading games on the Spectrum was the colourful border flickering around the screen while the cassette player did its thing. The stripes would constantly change position, occasionally pause, and then start flickering again. I must admit I’m not 100% sure as to why the colourful background was required to load a game, but I’d like to think it probably because it was a pretty good indication that something was happening ... Although whether that meant your game would actually load was another matter entirely!
As mentioned earlier in the post, the aim was to do all this fancy animation in modern CSS rather than resorting to images, GIFs, videos, or JavaScript. These all add page weight to the theme and would have a detrimental impact on readers of the blog. Plus, why would I use any of those technologies when it can all be done in CSS anyway?
Thankfully, modern CSS makes this surprisingly straightforward by using the @keyframes CSS at-rule, animation property, and the steps() timing function.
Rather than the stripes that were generated earlier smoothly scrolling around the screen in the background, I wanted them to jump between different positions, just like what happened on the original ZX Spectrum loading screen. This is where the CSS steps() function comes in. Take this short snippet of CSS:
animation: ns-spectrum-border 2s steps(1) infinite;CSS animations are often used with timing functions like ease, or linear, which is perfect if you want a smooth animation from one keyframe to the next, but this would make the stripes look more like a scrolling rainbow rather than the Spectrum loading screen! Pretty, but not what I want! Using steps(1) means the animation holds each position until the next keyframe, where it instantly jumps to the new position rather than transitioning smoothly. By combining this with irregular keyframe percentages and different background offsets, it creates the familiar flickering effect rather than a continuous scrolling animation, cool huh!
Accessibility and prefers-reduced-motion
It's important to remember that not everyone wants animations. For some, it's simply a personal preference, but for others, they can pose a genuine health risk.
As someone who experiences focal seizures, I know firsthand how unpleasant seizures can be, and I'm incredibly grateful that mine aren't triggered by flashing lights, colours, or motion. Unfortunately, others aren't so fortunate. People with photosensitive epilepsy can experience seizures triggered by certain flashing or rapidly changing visual patterns, while others may struggle with motion sensitivity or find animations distracting.
Ultimately, the reason doesn't matter. What's essential is that we, as developers, respect these preferences and give users control over their experience. Thankfully, modern CSS makes this straightforward with the prefers-reduced-motion media query, which can be used in two ways:
Opt In When There Is No Motion Preference
This is the recommended way to add an animation that allows a user to “opt-in” to animations as a progressive enhancement. By default, the Spectrum background is static cyan, the animation is only applied when a browser understands that the user hasn’t set a preference on animations.
/* Default: No animation */
.spectrum-border {
background-color: cyan;
}
/* Enhance when reduced motion is not requested */
@media (prefers-reduced-motion: no-preference) {
.spectrum-border {
animation: spectrum-flicker 2s steps(1) infinite;
}
}Turn the Animation Off for Reduced Motion
This basically reverses the functionality of the above code, by default the animation is enabled, then the media query is used to “cancel” the animation:
/* Default: animation */
.spectrum-border {
animation: spectrum-flicker 2s steps(1) infinite;
}
/* Disable animation as the "enhancement" */
@media (prefers-reduced-motion: reduce) {
.spectrum-border {
animation: none;
}
}My reasons for using the first (recommended) version are as follows:
- Accessibility first: Users requesting reduced motion never receive the animation. This also supports WCAG 2.2 Success Criterion 2.3.3: Animation from Interactions, where applicable.
- Seizure prevention: WCAG 2.2 Success Criterion 2.3.1: Three Flashes or Below Threshold requires flashing content to remain within safe thresholds. I believe the Spectrum border animation falls below these thresholds, although I haven't formally tested it. I've included reduced-motion support as an additional precaution, but this doesn't replace the need to meet the WCAG flashing requirements.
- Progressive enhancement: The static appearance works independently of the animation.
- Simpler CSS: No need to override or cancel an existing animation.
- Predictable behaviour: Browsers that don't support the media query retain the static version.
So that’s the animated background and overall look and feel all completed, what’s next?
Bringing the theme to Life with CSS Cursors
I’m old enough to remember when changing mouse cursors on a website was considered terrible practice, this was back in the late 1990s and early 2000s. When the CSS cursor property was introduced in CSS Level 2 published in 1998, there were multiple reasons it was considered bad practice at the time, these included:
- Loss of familiarity: Custom cursors replace established operating system conventions, making interactions less predictable and potentially confusing users.
- Accessibility: Custom cursors can override users' preferred cursor sizes and contrast settings, making them harder to see, particularly for users with visual impairments.
- Poor interaction feedback: Replacing familiar cursor styles can make it difficult to distinguish between clickable elements, selectable text, and other interactive components.
- Unnecessary downloads: Custom cursor images require additional resources, increasing page weight and potentially affecting performance, particularly on slower connections.
- Inconsistent browser behaviour: Historically, browser support for custom cursors varied significantly, resulting in inconsistent experiences across browsers and operating systems.
In fact, the CSS Cookbook from 2004 had an entire section dedicated to the cursor property, warning developers that changing familiar cursor behaviour could cause anything from mild annoyance to significant aggravation. I have to agree, I was never a fan of custom cursors, and it still irritates me when something is clickable but doesn't have the familiar hand cursor (cursor: pointer;) to indicate it!
That advice is now 22 years old, but it's just as relevant today. In fact, accessibility expert and advocate Eric Bailey wrote an article only five years ago (2021) titled "Don’t use custom CSS mouse cursors". With a title like that, from someone so well respected in the accessibility community, it's difficult to justify using custom cursors at all!
Interestingly though, there is no general WCAG 2.2 success criterion that prohibits custom mouse cursors. However, depending on their implementation, custom cursors could contribute to accessibility problems for users involving visibility, contrast, motion, and interaction.
So, if changing cursors can be so bad for usability and accessibility when done incorrectly, why is the cursor property still part of modern CSS specifications? Well, just because something is supported by a web standard doesn't necessarily mean it's good practice to use it! The property still serves legitimate purposes, such as indicating draggable elements, resizing controls, or providing feedback in drawing applications, not to mention backwards compatibility. The concern isn't changing the cursor itself, but replacing familiar operating system behaviour with something purely decorative that could confuse users or introduce accessibility issues.
Ultimately, CSS defines what developers can do, not necessarily what they should do! I firmly believe this sentence goes way beyond CSS when referring to technology on the modern web!
Right, enough rambling, Matt. Get to the point! Given everything I’ve written above about why custom cursors can be a usability and accessibility nightmare, I’m now going to do the very thing I’ve spent the last few paragraphs advising against! Yes, I’m adding a custom cursor to my little blog’s Spectrum theme. Hypocrisy? Perhaps … But please hear me out!
The difference is that I’m trying to do it responsibly, using progressive enhancement to introduce the cursor exclusively for the Spectrum theme, while leaving the default experience untouched. I’m also not going to pretend the potential usability and accessibility issues don’t exist. Quite the opposite! I’ve deliberately discussed both the good and bad points, so readers can understand the reasoning behind my decision and, more importantly, make up their own minds.
After all, part of the fun of building for the web is experimenting with what’s possible, even if that occasionally means bending a few best practices along the way. The important thing is understanding the consequences, being transparent about your decisions, and giving users a choice. And if anyone thinks this goes against everything I’ve just written, congratulations, you’ve been paying attention!
Implementing the Dizzy Cursor
And what better way to introduce a custom cursor to my Spectrum theme than by using one of my favourite characters from the games I reminisced about earlier in this post? Yes, you guessed it, it’s Dizzy! Everyone’s favourite egg-shaped adventurer is back, only this time he’s your cursor, ready to embark on his next big web adventure!
The first thing I had to do which I must admit was easier than I expected was finding images of Dizzy to recreate before using them as a custom cursor. I initially planned to use AI to convert rough graphics I found of Dizzy on the web into usable pixel art and then exporting them to either transparent PNG or maybe even a GIF? Modern browsers support a wide variety of image formats for custom cursors, including PNG, SVG, JPEG, WebP, AVIF, GIF, CUR, and ICO. Although support for animated formats varies between browsers, as outlined in the CSS Basic User Interface Module Level 4 specification and the MDN documentation.
It wasn’t until I started searching for these images on Google that I noticed something incredibly useful, there are a number of animation sprite sheets for Dizzy freely available online in PNG format. I won’t link to them directly, but they are super simple to find on Google Images. Their existence simplified things for me in three ways:
- The image format for the cursor was decided (PNG).
- It also gave me the opportunity to experiment with a little cursor animation that modern browsers also support: CSS Basic User Interface Module Level 4 - cursor and CSS Animations Level 1.
- No need to get AI to clean up random Spectrum screenshots found on the web, they could simply be cropped out of the sprite sheet as individual animation frames.
It’s worth pointing out that while the CSS specification allows animated cursors, that doesn’t necessarily mean every browser will support them. Browsers aren’t required to support every animated image format when used as a cursor, so don’t assume something will work just because it’s in the specification! I mean, modern support isn't perfect but at least support and specifications are better than 1998!
Custom Cursors, Image Formats, and CSS Animation
Thankfully, adding Dizzy as a custom cursor is relatively straightforward using the CSS cursor property and url() function. As mentioned earlier, modern browsers support several image formats for cursors, including PNG and SVG, although support for animated formats is a little less predictable. I've opted for indexed PNGs with transparency, which are ideal for Dizzy's limited colour palette and help keep file sizes to a minimum. There are a few limitations to consider, though. Browsers can impose restrictions on cursor dimensions. 32 × 32 pixels is still often recommended for compatibility, though the Spectrum theme uses 64 × 64 images, which modern browsers handle without issue. There's also something called a hotspot, which defines the exact pixel within the image that acts as the pointer. Without positioning this correctly, you could end up clicking somewhere other than where Dizzy appears to be standing, which isn't particularly helpful! The two numbers following url() below define the hotspot's horizontal and vertical coordinates, starting from the top-left corner of the image. For Dizzy, that's 32 52, roughly under his feet.
Of course, having Dizzy sitting there doing absolutely nothing would be a bit disappointing, so I've also used CSS @keyframes to animate him when hovering over links.
Rather than relying on animated GIFs or SVGs, which aren't consistently supported as animated cursors, the animation switches between individual PNG frames using the cursor property. Because the property uses discrete animation, and the timing function is step-end, the browser switches between images rather than attempting to transition between them. Just as I did with the background loading animation earlier in the post. Here's the CSS the Spectrum theme uses for the cursor and hover animation:
/* The default cursor for (non-animated) Dizzy */
@media (hover: hover) and (pointer: fine) {
html[data-theme="spectrum"] {
cursor: url("/img/cursors/spectrum/dizzy.png") 32 52, auto;
}
}
@media (hover: hover) and (pointer: fine) and (prefers-reduced-motion: no-preference) {
html[data-theme="spectrum"] a:hover {
cursor: url("/img/cursors/spectrum/dizzy-hover-1.png") 32 52, auto;
animation: ns-spectrum-dizzy-link 0.8s step-end infinite;
}
@keyframes ns-spectrum-dizzy-link {
0% {
cursor: url("/img/cursors/spectrum/dizzy-hover-1.png") 32 52, auto;
}
12.5% {
cursor: url("/img/cursors/spectrum/dizzy-hover-2.png") 32 52, auto;
}
25% {
cursor: url("/img/cursors/spectrum/dizzy-hover-3.png") 32 52, auto;
}
37.5% {
cursor: url("/img/cursors/spectrum/dizzy-hover-4.png") 32 52, auto;
}
50% {
cursor: url("/img/cursors/spectrum/dizzy-hover-5.png") 32 52, auto;
}
62.5% {
cursor: url("/img/cursors/spectrum/dizzy-hover-6.png") 32 52, auto;
}
75% {
cursor: url("/img/cursors/spectrum/dizzy-hover-7.png") 32 52, auto;
}
87.5% {
cursor: url("/img/cursors/spectrum/dizzy-hover-8.png") 32 52, auto;
}
}
}Hopefully, the code above is fairly self-explanatory. I do want to touch on that complex looking media At-rule though:
@media (hover: hover) and (pointer: fine) and (prefers-reduced-motion: no-preference){
}Here I’m checking 3 things in a user's browser:
hover: hover: Checks whether the user's primary input device supports hovering over elements, such as a mouse or trackpad.pointer: fine: Checks whether the user's primary pointing device supports precise interactions, rather than something less precise like a finger on a touchscreen.prefers-reduced-motion: no-preference: Checks whether the user has requested reduced motion through their operating system or browser settings.
If all three conditions are met the CSS is then applied. In the case of my animated Dizzy cursor, this means the animation is only enabled for users with a suitable pointing device who hasn't requested reduced motion. In summary, it's another example of progressive enhancement, ensuring that when a user’s browser doesn’t meet the conditions it retains the browser's default cursor behaviour.
Lastly, just because these conditions are met doesn’t guarantee the browser supports animated cursors! For that reason a users browser may display a static frame of Dizzy instead, or fall back to the standard pointer cursor if the cursor image isn’t supported at all.
And there you have it, a progressively enhanced custom cursor! Some users will see an animated Dizzy, others might see a static version, and those on touchscreens will simply retain their usual interactions. That’s the important thing about progressive enhancement: it’s not about giving everyone the same experience, but ensuring the experience works for everyone, regardless of their device, browser capabilities, or preferences. The animation is just a bit of nostalgic fun, not something users actually need to use the website!
The result is a little bit of ZX Spectrum nostalgia, recreated using CSS and a handful of tiny images. No additional libraries or JavaScript required. Dizzy might be looking for his next web adventure, but there’s no reason to make everyone else work harder to find theirs!
Lazy Loading, Pointer Events, and Accessibility
Now, as much as I love Dizzy, I don’t particularly want everyone visiting my blog downloading a collection of images just for a little ZX Spectrum nostalgia, especially when most visitors might never even select the Spectrum theme!
So, I needed a way to ensure the cursor images were only downloaded when actually needed (e.g. lazy load). Otherwise, I’d be making everyone pay a performance penalty for something purely decorative that they might never see or use. And knowing my blog could be faster, but wasn’t, would annoy me more than it would annoy my visitors! Clearly, something had to be done.
So, rather than including the cursor images directly in the Spectrum theme’s CSS, I’ve taken a slightly different approach using JavaScript to load them only when they’re actually needed.
Lazy Loading the Cursor
The primary mechanism I used was to defer loading any additional theme assets until the user interacted with the theme icon in the navigation. This ensures the page's content and default “System” theme take absolute priority over resources the users browser may never need. After all, there's little point in downloading a collection of images for a bit of ZX Spectrum nostalgia that a user may never experience!
But what if someone has already selected the Spectrum theme on a previous site visit? In that case, the JavaScript waits until the page has finished loading before using requestIdleCallback() to add the static Dizzy cursor. There's also a 1.5-second timeout and a setTimeout() fallback for browsers that don't support requestIdleCallback(). This keeps those decorative images out of the initial loading phase, giving more important resources priority.
Again, it's worth pointing out that requestIdleCallback() doesn't guarantee the cursor images won't affect Largest Contentful Paint (LCP), particularly if LCP occurs after the callback executes. However, deferring their loading until after the load event significantly reduces the likelihood of them competing with critical resources. As someone who cares deeply about frontend web performance, getting the actual content in front of users as quickly as possible will always take priority over a little ZX Spectrum nostalgia, even when Dizzy is involved!
However, if someone actively switches to the Spectrum theme, the static cursor is added immediately. After all, the user has specifically asked for the experience, so making them wait would be silly and frustrating!
Lastly, once a user switches away from the Spectrum theme, the JavaScript removes the cursor styles and any associated event listeners. This avoids leaving unnecessary event listeners hanging around for a feature that’s no longer being used. It also reduces unnecessary memory usage and ensures the browser isn’t doing additional work for something the visitor can no longer see.
Admittedly, the performance savings here are tiny, but it’s good practice to clean up after yourself, especially when dealing with purely decorative features. After all, there’s no reason for Dizzy to hang around consuming browser resources when nobody wants to play with him!
Only Downloading Animations When They're Needed
Initially, the cursor only needs one small PNG (dizzy.png). The other eight animation images needed to bring Dizzy to life aren’t loaded until someone actually hovers over a link. After all, why download images users may never see?
To achieve this, I use a pointerover event listener, which checks whether the pointer has entered a link using closest() method. The first time this happens, the animation CSS is added, allowing the browser to download the additional images only when they’re required. The event listener then removes itself, avoiding unnecessary checks as the pointer moves between elements, particularly if the user subsequently switches themes. As always with JavaScript, if you no longer need it, get rid of it!
The performance benefit here is that those additional images aren’t competing with more important resources during the initial page load, helping to preserve bandwidth and reduce unnecessary network requests, although the site uses HTTP/3 + QUIC, so network requests are less of a concern! Users who never hover over a link in the Spectrum theme won’t download them, nor will those who prefer reduced motion!
It’s a relatively small optimisation, but these things add up, particularly for visitors on slower connections or devices with limited resources. Eight small images might not sound like much, but why make a browser download something it doesn’t need? Dizzy might have been a bit of a hoarder, but that’s no excuse for making my users’ browsers behave like one!
Respecting Accessibility Preferences
I’ve also made sure Dizzy respects two important accessibility preferences because ZX Spectrum nostalgia shouldn’t come at the expense of accessibility!
Firstly, if someone has forced-colors: active enabled, such as when using Windows High Contrast Mode, Dizzy doesn’t make an appearance at all. Instead, the browser keeps its normal system cursor. I’ve also included a CSS fallback to disable the custom cursor and animation, just in case the styles somehow remain active.
Secondly, visitors who have enabled prefers-reduced-motion: reduce still get to enjoy Dizzy as a static cursor, but without any of the animation. Just like the Spectrum loading border I discussed earlier, the animation is only enabled when prefers-reduced-motion: no-preference is set.
An important point to note here, is I’m not downloading all the animation images only to disable them afterwards. When prefers-reduced-motion: reduce is set, they’re never downloaded! That means fewer unnecessary requests, less data transferred, and no unwanted animation. A small accessibility consideration that also happens to be good for web performance. What’s not to like, huh!
Layers of Progressive Enhancement
So, to summarise, visitors using the Spectrum theme with a suitable pointing device get one small, lazily loaded image of Dizzy. Hovering over a link triggers the download of the additional animation frames, while those using touchscreens, forced colours, or reduced motion get an experience that respects their device capabilities and preferences.
It’s another example of progressive enhancement, something I’ve mentioned quite a few times throughout this article. But there’s a good reason I keep talking about it! Ultimately, something that’s purely decorative shouldn’t come at the expense of accessibility, usability, or web performance. I might be enjoying a trip back to the 1980s, but that’s no excuse for dragging my visitors’ browsing experience back there with me!
Favicons and the Browser Cache
For the Spectrum tab icon, I’ve used the familiar rainbow from the original ZX Spectrum branding, cropped down to its diagonal colour bars: black (#000000), red (#FF1F1F), yellow (#FFC610), green (#3D9B00), and cyan (#00A7E1). An observant reader might notice these colours don’t quite match the Spectrum’s 15-colour palette I mentioned earlier in the post. That’s because the rainbow was part of the computer’s physical branding, rather than something its graphics hardware could actually display. A small distinction, but one I thought worth mentioning! When researching this post, I’d assumed the branding used the same colours the Spectrum could actually display. Apparently not, so til!
SVG Favicons, PNG Fallbacks, and Dynamic Updates
By default, my blog doesn't include a <link rel="icon"> in its HTML. Instead, the browser falls back to the favicon.ico at the root of the website, which contains the usual Nooshu logo at around 15 KB. This is also the icon you'll see when using the default System theme. Just a reminder, always make sure you have a favicon.ico in the root of your web server, else bad web performance issues could happen!
However, I wanted each of my custom themes to have its own favicon, including the Spectrum theme. After all, it would be a shame to go to all this trouble recreating a little ZX Spectrum nostalgia, only to leave the same old default site icon sitting in the browser tab!
Each custom theme has two favicon files, which are only added to the page when a user selects that particular theme. For the Spectrum theme, the configuration looks like this:
spectrum: [
{ href: '/img/themes/spectrum-favicon.svg', type: 'image/svg+xml' },
{ href: '/img/themes/spectrum-favicon-32.png', type: 'image/png', sizes: '32x32' },
],The SVG version is only 384 bytes, while the 32×32 PNG fallback is a 58 bytes bigger at a hefty 442 bytes! Both are completely self-contained, with no JavaScript or external resources, just the familiar Spectrum rainbow stripes.
So, why two images for each favicon? I added this so browsers that support SVG favicons can use the SVG, which offers the added benefit of remaining sharp even when scaled up on high-density displays. And for the small number of users on browsers without SVG favicon support, the PNG provides a fallback, this is known as graceful degradation.
You might wonder why I'm bothering with two formats when SVG support is so popular (92.55% globally). Well, as is often the case with web development, browser compatibility has a habit of making something relatively straightforward a little more interesting!
Firefox has supported SVG favicons since version 41, with Chrome and Edge following in version 80. Safari was rather late to the party, only introducing support in Safari 26, released in September 2025. Older versions, including Safari 18, don't support them.
But, here’s the issue: Safari also has another interesting quirk. When both ICO and PNG favicons are available, it can favour the ICO, regardless of the sizes attribute, bug report 315573 here. This means simply adding my Spectrum favicon alongside an existing ICO favicon link could result in Safari continuing to display the default Nooshu logo, which as mentioned before is boring!
To avoid this, my theme switcher removes any existing favicon links before inserting the ones belonging to the selected theme. Occasionally, you just have to be firm with browsers and tell them exactly what you want. No second-guessing, no creative interpretation, just use the exact icon I asked for!
The same approach applies to all my other custom themes. Light and dark have their own versions of the Nooshu logo, while Phosphor, Amber, Commodore 64, Game Boy, IBM PC DOS, and Macintosh each have their own themed icons. Switching back to System removes the custom favicon links, allowing the browser to fall back to root favicon.ico again.
Lazy Loading the Favicons
Now, given how much I've already discussed web performance throughout this article, it would be rather embarrassing if I started downloading a collection of decorative favicons that visitors might never actually use or see!
So, just like the other theme assets, none of these custom favicons are referenced in the initial HTML. Even opening the theme switcher doesn't trigger the favicon downloads. The preloading that happens when opening the theme menu is reserved for only theme stylesheets.
Instead, the Spectrum favicons are loaded in two situations:
- When someone selects the Spectrum theme: The favicon links are inserted into the Document Object Model (DOM) immediately. The user has explicitly chosen the theme, so there's no reason to delay updating the browser tab.
- When Spectrum was selected during a previous visit: The switcher waits until the page's
loadevent has fired, then usesrequestIdleCallback()with a 1.5-second timeout and asetTimeout()fallback before inserting the favicon links. This is also when the static Dizzy cursor is allowed to load.
The second approach is particularly important for web performance. It means returning visitors don't have additional decorative resources competing with the page's render-blocking assets during initial page load.
There is a minor trade-off. The browser might briefly display the default Nooshu favicon before switching to the Spectrum version. Personally, I'm fine with that. I'd much rather prioritise getting the actual page loaded and usable than worry about whether a tiny icon in the browser tab has caught up! I’d be interested to know if any readers actually, notice these little details, Or is it me just obsessing?! Most likely the latter, to be honest!
As mentioned earlier in the post, it's worth mentioning that requestIdleCallback() doesn't guarantee these resources will never compete with page rendering or affect LCP. However, waiting until after the load event significantly reduces the likelihood of them interfering with the initial page load.
Finally, I've made sure the switcher doesn't repeatedly update the favicon unnecessarily. It remembers which theme's icons are currently active, so selecting the same theme again doesn't trigger another update. Switching to a different theme, or returning to System, updates the icons as required. This avoids unnecessary DOM changes and resource requests, although in some instances, browsers may already have the favicon files cached.
The end result is a collection of theme-specific favicons that are only introduced when they're actually needed. No additional JavaScript libraries, no unnecessary downloads for users who stick with the default theme, and no decorative assets competing with the initial page load.
Just a small detail that adds a little more ZX Spectrum nostalgia for those who want it, without making every other user’s browser do unnecessary work!
Forcing a Refresh Without a Fresh Download
I’ve always found changing favicons to be a rather tedious and frustrating experience. Even after multiple hard refreshes in the browser, the old ones seem to hang around like a deprecated npm package. Nobody wants them, nobody maintains them, but apparently removing them would break everything!
Part of the problem is that browsers often cache favicons differently from ordinary images, and simply changing the href of an existing icon link doesn’t always convince the browser to use the new one. Adding a query string, such as ?v=2, is one way to encourage it to notice the change. Unfortunately, because the query string forms part of the cache key, it also means another network request to fetch it, so, even if the favicon is already cached under a different URL, it will still be downloaded. Do that every time a user switches themes, and you’re unnecessarily downloading resources the browser may already have! This isn't exactly ideal when you’re trying to keep things as lightweight as possible!
The solution I eventually settled on was to use URI fragments, this is the bit at the end of a URL that starts with #.
Unlike query strings, fragments aren't sent to the server as part of an HTTP request. This means I can change a favicon's URL from spectrum-favicon.svg#1 to spectrum-favicon.svg#2 without changing the resource the browser requests. Both URLs point to exactly the same file, so if the browser already has it cached, there's no need to download it again!
The idea is fairly simple. By changing the fragment, I'm giving the browser a different favicon URL to work with, and thus hopefully encouraging it to update the tab icon without downloading the same image again. Essentially, I'm trying to convince the browser that something has changed, without making it do any unnecessary work. Who would have thought such a small detail would involve so much work, not to mention hacking around the browser’s aggressively stubborn favicon cache!
Here's the JavaScript I use to force a browser to update the favicon:
function forceFavicon(icons) {
// Increment the counter each time the favicon changes.
// This gives each update a unique URL fragment.
faviconNonce += 1;
// Remove any existing favicon links, including
// the older "shortcut icon" format.
for (const node of document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]')) {
node.remove();
}
// Create a fresh favicon link for each supplied icon.
for (const icon of icons) {
const link = document.createElement('link');
// Tell the browser this link represents a favicon.
link.rel = 'icon';
link.type = icon.type;
// Include the icon dimensions when provided.
if (icon.sizes) {
link.setAttribute('sizes', icon.sizes);
}
// Add the unique fragment to encourage the browser
// to update the icon without changing the HTTP
// resource or its cache key.
link.href = `${icon.href}#${faviconNonce}`;
// Add the new favicon link to the document.
document.head.appendChild(link);
}
}Each time a user switches themes, the function increments a counter, removes the existing favicon links, and creates new ones with an updated fragment.
For example, selecting the Spectrum theme adds two favicon links, one for the SVG and another for the PNG fallback. Switching back to the System theme replaces these with a single link to the root favicon.ico.
The first time someone selects Spectrum, the browser downloads the two images. On subsequent visits to the theme, those resources can be reused from the browser's cache, provided they haven’t changed. The changing fragment encourages the browser to update the tab icon. I say encourages because browsers don't all handle favicons in quite the same way, so there's no guarantee this approach will work everywhere. That said, it's certainly more reliable than anything else I've tried over the years! Apparently, even when you tell a browser exactly what you want it to do, there's still no guarantee it'll listen!
The important point that I’ve been wanting to achieve is having functionality that allows me to change the favicon URL without changing the underlying HTTP resource. This then means no additional icon downloads, no unnecessary cache busting, and hopefully no more staring at a browser tab wondering why it's still displaying the wrong icon!
Caching the Spectrum Favicons
Both Spectrum favicon files are served with the following HTTP response header:
Cache-Control: public, max-age=2419200That's 28 days of browser caching, the same duration I have used for the site's default favicon.ico in my site root.
I've deliberately avoided using the immutable directive because the filenames don't change when I update the images. If I decide to make another adjustment to the Spectrum rainbow, I want browsers to eventually pick up the new version rather than treating the existing file as something that will never change.
Of course, that also means visitors might continue seeing the previous version until their cached response expires. For something as small and decorative as a favicon, I'm perfectly happy with that trade-off.
Using a different query string every time someone changes themes would defeat much of this caching benefit, potentially forcing the browser to download an image it already has cached.
And considering we're talking about a tiny image sitting in a browser tab, that seems totally unnecessary!
Why I Still Have a Default favicon.ico
There’s another important detail worth mentioning. Although my blog doesn’t explicitly reference favicon.ico in its HTML templates, the file still exists in the website’s root directory.
This is intentional, and I mentioned it earlier in the post. It’s something I've written about before in Why you should be testing your 404 pages web performance, way back in 2020! Wow, doesn't time fly when you're busy living through a global pandemic and being diagnosed with brain cancer! Not quite how I'd planned to spend the first half of the decade, but there we go!
A very brief overview of the post I wrote is: when a webpage doesn’t explicitly declare a favicon, browsers often request the root favicon.ico automatically. If it doesn’t exist, the resulting 404 pages could include HTML, CSS, JavaScript, and images, which I can almost guarantee will be considerably larger than that tiny favicon the browser is requesting!
When I originally researched this back in 2020, I discovered some interesting figures from the June 2020 HTTP Archive crawl.
Of the unique 404 responses recorded, 632,384 URLs (21.51%) were requests for missing favicons. Even more surprisingly, 1,757 of the largest error responses (15.1%) were caused by requests for the same missing file.
The worst example was a 6.7 MB HTML response generated because a browser couldn't find a favicon.ico in the site root. Firefox spent 17.3 seconds downloading it!
That's 6.7 MB of HTML and 17.3 seconds spent requesting an image that didn't exist, all for something most visitors probably wouldn't even notice was missing.
That’s not exactly an achievement worth putting on your CV (resume)!
So let this be a reminder that seemingly insignificant resources can still have a measurable impact on web performance, particularly when the same unnecessary request happens across multiple pages!
Theme Switching Without Compromising Performance
This blog has nine different colour themes. That's potentially a lot of CSS, favicons, and, in the Spectrum theme's case, cursor images to download for a user who only came here to read a blog post!
By default, my blog respects a user's operating system preference for light or dark mode, using the prefers-color-scheme CSS media feature. There's a good reason for this. The user has already gone to the trouble of telling their operating system which colour scheme they prefer, so who am I to decide otherwise? As web developers, the browser gives us everything we need to respect that preference, and frankly, it would be terribly rude not to!
Of course, respecting a user's preference doesn't mean taking away their choice. Visitors can still select any of my nine themes, regardless of their operating system settings. After all, if everyone were happy with just light and dark mode, I wouldn't have spent quite so much time writing this blog post!
The architecture I wrote to handle the themes efficiently needed to achieve three things, all with web performance, accessibility, and progressive enhancement in mind:
- Apply the chosen theme before the first paint: Nobody wants to see the wrong colours briefly flash across their screen before their preferred theme appears!
- Keep unnecessary resources off the critical path: Stylesheets, favicons, and cursor images for other themes shouldn't be downloaded until they're actually needed. There's no point making users download resources they will never use!
- Make the theme switcher accessible by default: Use standard semantic HTML so keyboard and screen reader users can interact with the theme switcher, while ensuring the page remains usable when JavaScript is disabled, or more likely fails to load. I’ll mention it again, but it’s just Progressive enhancement doing what it does best, building for all users, regardless of device or network conditions!
Preventing Flash of the Wrong Theme
A flash of the wrong theme is essentially the colour equivalent of a flash of unstyled content (FOUC). It happens when the server renders the HTML without a data-theme attribute on the <html> element.
To avoid this, my base stylesheet sets color-scheme: light dark on the <html> element. This allows light-dark() and browser-controlled elements, such as form controls and scrollbars, to automatically follow the user's preferred colour scheme.
I call this the "System" theme, and it's my blog's default. Importantly for a users perceived performance, it requires no additional downloads or JavaScript. Everything needed to render the correct colours is already included in the initial stylesheet from the very first network request.
Unfortunately, the problem appears on a return visit when someone has previously selected Spectrum, Phosphor, or any theme other than the default "System" theme.
The problem is that the server cannot access the browser's localStorage, so the HTML arrives without knowing which theme the visitor previously selected.
My first attempt was to wait for the DOMContentLoaded event before applying the saved theme. That made things worse! Determined to optimise performance, I also tried a deferred script, to keep it from blocking HTML parsing. Unfortunately, that meant the browser would render the default "System" theme before JavaScript retrieved a users saved preference from localStorage and applied the correct colours.
The result? An ugly flash of the wrong theme, followed by a repaint. The Spectrum theme was particularly awful because its colourful loading bezel also changes the page layout. So, rather than a simple colour change, visitors got a lovely layout shift thrown in for good measure! Not exactly the user experience I was aiming for!
Of course, this all assumes I actually have repeat visitors. For all I know, nobody has ever noticed any of this. Except me, obviously!
The fix is a tiny bootstrap, called _theme-init.js it sits in my public/js/ folder, that runs while the HTML parser is still in <head>. In production, it is in-lined, so Lighthouse does not count a separate render-blocking script request, and it is deliberately neither defer nor async.
A Content-Security-Policy(CSP) hash allows that exact in-line script, and the hash never needs to change because the initialisation (init) script never changes. The fingerprinted stylesheet URLs live in a separate meta tag in the <head> as seen in the code below, which means editing a theme's CSS does not change the init script or its hash:
<meta name="ns-theme-css" content='{"spectrum":"/css/themes/spectrum-1a2b3c4d5e.css.br", …}'>
<script>
/* inlined theme-init 1,400 bytes */
</script>The script reads one localStorage key, called theme, and accepts it only if it is in a hard-coded allowlist (e.g. light, dark, phosphor, amber, c64, gameboy, ibm-dos, macintosh, spectrum). Anything else, including a missing key, leaves the document alone and the OS preference stands.
A valid ID does two things before the parser continues:
// Retrieve the user's previously selected theme from localStorage
const storedTheme = localStorage.getItem('theme');
// Check that a stored theme exists and is in the allowlist
if (storedTheme && PINNED_THEME_IDS.includes(storedTheme)) {
// Set the data-theme attribute on the root <html> element
document.documentElement.setAttribute('data-theme', storedTheme);
// Inject the selected theme's stylesheet into the document as it's being parsed
document.write('<link rel="stylesheet" href="' + THEME_CSS[storedTheme] + '">');
}It’s not very often you see document.write() being used in modern JavaScript, let alone get a legitimate reason to use it! There are two notable explanations for this:
- It's a potential security risk: much like
eval(), particularly when handling untrusted input. You can read more about the dangers ofeval()on my favourite website, Mozilla Developer Network (MDN). - It can do some spectacularly bad things when used incorrectly: Like completely obliterating your entire webpage! HTML, CSS, JS, DOM, the lot! Not exactly what you'd call a graceful degradation.
Having said that, when used carefully, document.write() can actually be rather useful! In this case, it's doing much of the heavy lifting to prevent that annoying flash of the wrong colour theme.
The important point is when it runs. Because my script executes while the browser is still parsing the initial HTML, document.write() inserts the selected theme's stylesheet directly into the HTML parser's stream. This makes the stylesheet render-blocking, meaning the browser waits for it before rendering the page. By that point, the <html> element already has data-theme="spectrum", and the Spectrum theme's CSS custom properties are ready to go. No flash of the default colours, and everyone's happy! It isn’t often that you see a render blocking resource as a positive point when it comes to web performance and usability, but in this case it is!
If I applied the attribute and loaded the stylesheet later, the browser could render the default colours first, which defeats the whole point of this exercise!
Of course, there's a catch. Timing is everything! Try the same trick in the deferred theme switcher I mentioned earlier, after the document has finished loading, and document.write() would likely wipe out the entire page. A rather dramatic way of changing a few colours, and not at all the intention!
That's why subsequent theme changes use document.createElement('link') instead. It safely adds the stylesheet without risking the complete destruction of my lovingly crafted HTML. Which, as you can probably imagine, I'd quite like to keep!
The result of all this tiny JavaScript bootstrap is that one stylesheet is requested here. The other eight stay out of the HTML, out of HTTP Link headers, and out of the bootstrap itself!
Lazy Loading, Resource Prioritisation, and Browser Caching
To maximise page performance, the main stylesheet is in-lined directly into the HTML in production, before the HTML is compressed using Brotli at level 11. On a user's first visit, the “System” theme is selected by default. I've deliberately built things so that no additional stylesheets, favicons, or other theme assets need to be downloaded. Everything required is already there in the initial HTML response!
Each theme has its own CSS file under public/css/themes/, which is only downloaded when that theme is selected. This keeps the initial CSS payload as small as possible, avoiding unnecessary downloads and keeping the browser's critical rendering path nice and lean!
The entire theme functionality has been designed so that CSS and other assets belonging to unused themes never get in the way of the browser's critical rendering path. If you're happily reading in your preferred colour theme, there's absolutely no reason to download assets for the other eight!
I've split the build process into development and production tasks. During development, asset optimisation is kept to a minimum because I’m the only one who will see it! Production is a different story. Each theme's CSS is minified using CleanCSS, hashed, and then Brotli-compressed at level 11. The resulting filename looks something like /css/themes/spectrum-<hash>.css.br.
Because the filename contains a hash of the minified CSS, any changes produce an entirely new URL. This means the browser can safely cache the file very aggressively, there’s no need to worry about outdated assets, an example of this aggressive caching is below:
Cache-Control: public, max-age=31536000, immutable
Content-Type: text/css
Content-Encoding: brA year (31536000 seconds) with immutable is the opposite of the favicon caching approach I mentioned earlier. Unlike my favicons, which keep the same filenames, each theme stylesheet has a content hash in its URL. When the CSS changes, so does the hash, meaning the next build references a new URL and the browser fetches the updated stylesheet. The old version can eventually be discarded from the cache automatically by the browser. Winner winner chicken dinner!
That's why I love asset fingerprinting for web performance. Once automated, it's a genuine set-it-and-forget-it optimisation. Just don't use immutable on a favicon you expect the browser to refresh while its URL stays the same!
Those /css/*.css.br files in the <meta> tag also bypass the Cloudflare Pages Function serving JavaScript. Instead, Cloudflare serves them directly with Content-Encoding: br, so the browser receives Brotli-compressed CSS, decompresses it, and caches it against the fingerprinted URL. No unnecessary JavaScript or Function execution involved!
The Popover API, matchMedia(), and Progressive Enhancement
As mentioned, the theme control in the top right of the navigation is a button and a set of radio buttons. The menu is not a custom widget drawn in JavaScript.
<button type="button" id="themeToggle"
popovertarget="theme-menu"
aria-expanded="false"
aria-controls="theme-menu"
aria-label="Colour theme: System">
<!-- one SVG per theme, CSS shows the current one -->
</button>
<div id="theme-menu" popover="auto">
<fieldset>
<legend>Appearance</legend>
<label>
<input type="radio" name="site-theme" value="system" checked
data-giscus="preferred_color_scheme" data-label="System">
<span>System</span>
</label>
<!-- Light, Dark -->
</fieldset>
<fieldset>
<legend>Retro</legend>
<!-- Phosphor through ZX Spectrum -->
</fieldset>
</div>Both popovertarget and popover="auto" are native HTML. Browsers supporting the Popover API handle opening, closing, Escape, clicking outside, and placing the menu in the top layer. All without a single line of JavaScript!
The switcher itself uses native radio buttons grouped into two fieldsets, “Basic” and “Retro”, complete with proper legends, labels, and built-in keyboard navigation. No need to reinvent something browsers already do perfectly well!
The “System” theme is checked by default in the HTML, so even with JavaScript disabled, or when it fails to load, the menu remains accessible, and the page respects the user's operating system colour preference.
The switcher script simply enhances this existing functionality. It reads and saves the user's preferred theme in localStorage, applies the corresponding colours, and loads any additional theme assets when required. Without it, the radio buttons remain usable as form controls, but selecting another theme won't change the page's appearance.
Essentially, Native HTML and the Web Platform do the heavy lifting. JavaScript just adds the finishing touches!
Once running, the switcher syncs the selected radio button with the data-theme attribute set earlier by the bootstrap script. It also updates the switcher's accessible name to reflect the active theme, for example, Colour theme: ZX Spectrum.
The Popover's toggle event handles aria-expanded, moves focus to the selected radio, positions the menu beneath the button, and preloads the theme stylesheet if a pointer event hasn't already triggered it. Scrolling closes the menu, while resizing repositions it when open.
Importantly, only a change event on the radio buttons calls the function applyThemeChoice(). Everything else simply manages the menu's behaviour, keeping theme selection separate from the user interface.
Next up is matchMedia(), which allows the browser check device capabilities and user preferences. Rather than making assumptions about how someone is viewing the page, we can get the browser to tell us!
(hover: hover) and (pointer: fine): Checks whether the device has a precise pointer capable of hovering before enabling the Dizzy cursor. Touchscreen devices without these capabilities skip the unnecessary image download.(forced-colors: active): Disables the custom cursor in Windows High Contrast and other forced-colour modes. CSS provides an additionalcursor: autofallback, just in case!(prefers-reduced-motion: reduce): Respects the user's motion preferences by skipping the animated cursor's hover-frame download and disabling the colour transition onbody.(prefers-color-scheme: dark): Watches for changes to the user's preferred colour scheme, but only when the visitor is using the default “System” theme (<html>has nodata-themeattribute).
Finally, there's Giscus, which handles the blog's comments and only loads when someone opens the comment's disclosure e.g. user-driven lazy-loading for optimal performance. Its initial theme is determined by the document's current data-theme attribute in the root <html>. If no attribute is present, that means the Giscus theme should use preferred_color_scheme, while Spectrum, Light, Game Boy, and Macintosh Classic use Giscus's light theme. The remaining themes use dark.
If someone changes their theme while the comments are already open, the switcher sends a message to the Giscus iframe to update its appearance like so:
iframe.contentWindow.postMessage(
{ giscus: { setConfig: { theme: getGiscusTheme() } } },
'https://giscus.app'
);What the ZX Spectrum Theme Says About the Web
I have to say, the amount of modern browser technology that has gone into recreating this little slice of computing nostalgia has been quite impressive! Who would have thought that making a website look like a computer from the 1980s would involve so much modern technology?
The Web Platform has matured enormously over the past few years, thanks to the tireless efforts of organisations, browser vendors, independent contributors, and initiatives such as:
- W3C (World Wide Web Consortium)
- WHATWG
- Ecma International (TC39)
- W3C WebDX Community Group
- W3C Web Accessibility Initiative (WAI)
- Igalia
- Bocoup
- Google (Chrome/Chromium)
- Mozilla (Firefox)
- Apple (Safari/WebKit)
- Microsoft (Edge)
- Interop
- Web Platform Tests (WPT)
- Baseline
- Web Features
- Open Web Docs
- MDN Web Docs
- Web Platform Dashboard
- Open Web Advocacy (OWA)
Without the contributions of tens of thousands of people from across the world, I'm fairly certain this little project would either:
- Not have been possible: at least not in the way I wanted.
- Have required a small mountain of JavaScript: making it unnecessarily complicated, less performant, and potentially frustrating for both myself and anyone unfortunate enough to visit!
Thankfully, in 2026, the Web Platform does much of the heavy lifting for us, exactly as it has been designed for!
Modern CSS can recreate the colours, layouts, animations, and visual quirks of a 1980s computer without relying on JavaScript for every little detail. Native HTML provides much of the functionality and accessibility out of the box, while a relatively small amount of JavaScript progressively enhances the experience where required.
And that's what I particularly love about this project. It's possible to recreate something wonderfully nostalgic without recreating all the technical limitations that came with it! The end result is a website that celebrates the past while taking full advantage of modern browser capabilities, progressive enhancement, accessibility, and web performance.
Of course, none of this happens accidentally. Standardisation, interoperability, and collaboration on a global scale are what make the modern web possible.
Since its invention, the web has certainly seen the good, the bad, and the downright ugly. I’ve been building websites long enough to remember when getting something working across browsers required patience, determination, and occasionally questioning your career choices!
Having been a Frontend Developer through both browser wars, I can safely say you couldn't pay me enough to go back to those days. Browser-specific hacks, inconsistent implementations, and endless frustration were hardly the highlights of my career!
From my perspective as a Frontend Developer, we really are living in a golden age of the Web Platform. We have more native capabilities, better interoperability, and fewer reasons to reach for JavaScript dependencies to solve problems the browser can already handle.
And perhaps that's my biggest takeaway from this entire project. Every so often, the best way to build something that feels like 1986 is to embrace everything the web has achieved in the 40 years since! Who'd have thought?!
Web Technologies Used in the Theme
When I started building this little tribute to my childhood, I certainly didn't expect to end up writing about quite so many web technologies, techniques, and other bits of web-related wizardry! What started as a bit of ZX Spectrum nostalgia somehow turned into a fairly extensive tour of the modern Web Platform.
Just look at everything we've managed to cover!
CSS
- Animatable properties (discrete animation)
animationanimation-timing-function- Attribute selectors
background-positionbackground-repeatbackground-sizecalc()color-scheme- CSS animations
- CSS at-rules
cursor- Custom properties (
--*) <easing-function>, includingease,linear, andstep-endfont-family(system monospace)forced-colors<hex-color>hover@keyframes<length>, includingvhlight-dark()linear-gradient()- Logical properties
@mediamin-block-size<named-color>pointerprefers-color-schemeprefers-reduced-motionrepeating-linear-gradient()steps()url()var()
HTML
aria-controlsaria-expandedaria-label<button>, includingpopovertargetdata-*- Favicon
<fieldset><iframe><input type="radio"><label><legend><link>- Link header
popoverrel, includingicon<script>(deferandasync)
Image Formats
- AVIF
- Image file types (PNG, JPEG, GIF etc)
- PNG
- SVG
- SVG as an image
- WebP
JavaScript and Web APIs
changeeventdocument.createElement()document.write()DOMContentLoadedElement.closest()eval()loadeventlocalStoragematchMedia()MediaQueryList- Pointer events
pointerover- Popover API
postMessage()requestIdleCallback()setTimeout()toggleevent- Top layer
URL.hash(URL fragments)URL.search(query strings)
HTTP, Caching, and Performance
- Brotli compression
Cache-Control, includingmax-ageandimmutableContent-Encoding- Content Security Policy
Content-Type- Critical rendering path
- Cumulative Layout Shift (CLS)
- Graceful degradation
- HTTP caching
- HTTP/3
- Largest Contentful Paint (LCP)
Link- MIME types
- Perceived performance
- Progressive enhancement
- QUIC
- Web performance
Some of these have only been touched on briefly, while others have been essential to making the whole theming experience work. Either way, it's quite remarkable how much of the modern Web Platform we've managed to squeeze into something inspired by a computer from 1982!
And, in typical fashion, I've somehow managed to turn what should have been a relatively short blog post into something resembling a small technical manual. Sorry about that! Clearly, knowing when to stop writing is another skill I need to work on.
On a more personal note, I'd absolutely love it if the Oliver Twins somehow came across this little tribute. Their Dizzy games were such a large part of my childhood, and I'd like to think they'd appreciate how something they created all those years ago continues to inspire me today. It's quite a lovely thought that the games I spent so many hours playing as a child are still influencing the things I build nearly four decades later! Now I feel ancient! 👨🏻🦳
If you've made it this far, thank you! I sincerely hope you've found this interesting, informative, and perhaps even a little nostalgic. If you haven't already, why not check out the ZX Spectrum theme in all its 8-bit glory using the theme button in the top-right corner of the page? As always, I'd love to hear your thoughts, so if you have any comments or feedback, please do let me know!.
Post changelog:
- 27/12/03: Initial post published.