Dark theme with media queries, CSS and JavaScript

Posted by Michał ‘mina86’ Nazarewicz on 28th of March 2021

Split view of Tower Bridge during the day and at night.
(photo by Franck Matellini)

No, your eyes are not deceiving you. This website has gone through a redesign and in the process gained a dark mode. Thanks to media queries, the darkness should commence automatically according to reader’s system preferences (as reported by the browsers). You can also customise this website in settings panel in top right (or bottom right).

What are media queries? And how to use them to adjust website’s appearance based on user preferences? I’m glad you’ve asked, because I’m about to describe the CSS and JavaScript magic that enables this feature.

Media queries overview

body { font-family: sans-serif; }
@media print {
	body { font-family: serif; }
}

Media queries grew from the @media rule present since the inception of CSS. At first it provided a way to use different styles depending on a device used to view the page. Most commonly used media types where screen and print as seen in the example on the right. Over time the concept evolved into general media queries which allow checking other aspects of the user agent such as display size or browser settings. A simple stylesheet respecting reader’s preferences might be as simple as:

body {
	/* Black-on-white by default */
	background: #fff;
	color: #000;
}
@media (prefers-color-scheme: dark) {
	/* White-on-black if user prefers dark colour scheme */
	body {
		background: #000;
		color: #fff;
	}
}

That’s enough to get us started but not all browsers support that feature or provide a way for the user to specify desired mode. For example, without a desktop environment Chrome will report light theme preference and Firefox users need to go deep into the bowels of about:config to change ui.systemUsesDarkTheme flag if they are fond of darkness. To accommodate such situations, it’s desirable to provide a JavaScript toggle which defaults to option specified in system settings.

Fortunately, media can be queried through JavaScript and herein I’ll describe how it’s done and how to marry theme switching with browser preferences detection. TL;DR version is to grab a demonstration HTML file which includes a fully working CSS and JavaScript code that can be used to switch themes on a website.

TLS is a yes

Posted by Michał ‘mina86’ Nazarewicz on 15th of April 2016

An image of Hollywood’s idea of ‘hacking’
(still from movie Swordfish)

Let’s Encrypt has left beta and to celebrate, this blog gained TLS support. \o/ If all goes well it’ll become the default including an HSTS header so everyone can benefit from improved privacy†.

Website move

Posted by Michał ‘mina86’ Nazarewicz on 1st of April 2016

Photo of a truck on a road.
(photo by Ikiwaner)

Some regular visitors of the web site may be aware that the page used to run on Jogger.pl platform. Some will also be aware that the service closes shop, an act which forced me to move to another hosting.

In moving the page, I’ve tried to keep old URLs work so even though canonical locations for posts have changed, the old links should result in a correct redirect.

This is also true for feeds but while Jogger provided customisation options (RSS and Atom, excerpts only, no HTML and posts count), currently only full-content HTML Atom feeds limited to newest ten entries are provided.

If anything broke for you, please do let me know at mina86@mina86.com.

I have not yet figured out what to do with comments which is why commenting is currently unavailable. Since I want my whole page to be completely static, I’m planning on using a third-party widget. So far I’ve narrowed the choice down to HTML Comment Box and the new hotness, Spot.IM. Any suggestions are also welcome.

Graph showing drop in response time from 300 ms to 60 ms

On the bright side, the page now loads five times faster! Jogger.pl took its sweet time when generating responses. A static page and better optimised infrastructure of my current provider allows to drop response time from 300 to 60 ms.

Mobile is the Future

Posted by Michał ‘mina86’ Nazarewicz on 17th of March 2015

Photo of a smashed mobile phone.
(photo by Cory Doctorow)

A few days ago I received an email from Google Wembaster Tools saying no more no less but: ‘Your webpage sucks on mobile devices!’ Or something. Now that I think of it, I could have been worded slightly differently. The gist was the same though.

I never paid that much attention to how my site looks on phones and tables. I’ve made sure it loaded and looked, but apart from that never spent much time on the issue. I always thought optimising for a small screen would be a lengthy and painful process. How mistaken I was!

In my defence, when I last looked at the problem, state of mobile browsers was different; now there are two things to do. First, add a viewport meta tag, e.g.:

<meta name=viewport
      content="width=device-width, initial-scale=1">

and then use min-width or max-width CSS media queries. Admittedly the second part may take some time, but if your layout uses simple markup rather than being TABLE-based, reading the excellent article on A List Apart might turn out to be the most time consuming step.

If you haven’t already, do take a look at whether your website looks reasonably well on small screens. Apparently mobile is the future, or some such.

The ‘bad’ news is that I’ve dropped endless scroll feature. This is because in narrow layout the sidebar moves to the bottom and endless scrolling would make it unreachable since it would run away all the time.

The fifth generation

Posted by Michał ‘mina86’ Nazarewicz on 29th of March 2013

Southwark Cathedral with The Shard skyscraper in the background
(photo by Tristan Surtel)

This day must have come sooner or later. Even more so since I love squeezing every byte out of the data being sent over the network, which is why source of this website is so unreadable (don’t worry though, readable sources are available in a git repository).

So yeah. I’ve switched this website to HTML5 with some of it’s new elements and optional tags removed. After years of using XHTML 1.1 it feels a bit weird not closing tags, but I guess a few saved bytes are worth it, aren’t they? ;)

I’ve even got my electric slash working in Emacs’s html-mode (ie. if I press slash after < sign, inner most element is closed automatically).

Unfortunately, not all is so shiny. For some reason, automatic pagination on entries list page and ‘load content’ link stopped working under Opera. The way those work is by making an XMLHttpRequest and injecting portion of the fetched document in appropriate place. For some reason, Opera ends up with a DOMException: INVALID_STATE_ERR.

Przesiadka na Joggera

Posted by Michał ‘mina86’ Nazarewicz on 12th of February 2008

Zdjęcie rusztowania przy wieżowcu.
(fot. Kiril Havezov aka walker_M)

Niecałe pięć godzin temu założyłem konto na Joggerze i rozpocząłem pracę nad przeniesieniem strony na tą nową… platformę. Powód jest bardzo prosty — lenistwo. Do tej pory, pomimo, że strona generowana była za pomocą skryptów napisanych w Perlu, aby dodać jakiś artykuł musiałem bawić się w przesyłanie plików za pomocą protokołu FTP.

Przez kilka godzin miałem jeszcze ambitny plan napisania czegoś samemu, jednak, gdy odkryłem, iż Jogger umożliwia podpięcie domeny plan legł w gruzach. Teraz jestem już na półmetku. Pozostaje pozmienianie wpisów w DNS-ach i przerzucenie artykułów do Joggera. Biorąc pod uwagę, że już po północy, powinienem dziś skończyć. ;)

Oczywiście zakładając, że faktycznie można podpiąć Joggera pod własną domenę, bo zaczynam mieć co do tego wątpliwości… Update: No i jest! Przy trzeciej próbie w końcu domena została podpięta.

Ah wakacje…

Posted by Michał ‘mina86’ Nazarewicz on 12th of February 2007

Zdjęcie nóg w basenie w słoneczny dzień.
(fot. Matthew Bowden )

Wakacje, a więc nadszedł czas na uporządkowanie wszystkich spraw związanych ze stroną. Przede wszystkim słówko o sprawach zaległych: Otóż już od bardzo dawna obiecywany zrzut X-Forum jest dostępny i można go sobie czytać. Należy również zauważyć, że brak nowych newsów nie oznacza wcale, że na stronie nic się nie dzieje -- w międzyczasie pojawiły się nowe artykuły, a także co i rusz poprawiałem odrobinę techniczne aspekty strony.

Jeśli chodzi o sprawy techniczne to w ostatnich dniach zmieniłem sporo, choć przeciętny użytkownik prawdopodobnie tego nie zauważy. Dodałem arkusz styli do wydruku, dzięki czemu strona powinna się ładnie drukować bez zbędnych linków i obrazków. Postarałem się także o zgodność ze standardami W3C XHTML 1.1 i W3C CSS 2.1 jak i wytycznymi WAI WCAG.

Niejako efektem ubocznym tych zmian są klawisze skrótu jakie dodałem w pasku nawigacyjnym na dole strony. Zależnie od przeglądarki, którą używasz skorzystanie z nich może odbywać się w różny sposób. W Operze (przy domyślnej konfiguracji) należy wcisnąć Shift+Esc i pojawi się lista dostępnych klawiszy skrótu. Mam nadzieję, iż to ułatwi nawigacje po stronie.

The beginning is a very delicate time

Posted by Michał ‘mina86’ Nazarewicz on 8th of May 2006

Zdjęcie promieni słońca przebijających się przez chmury.

Jak mawiają Starożytne Gumisie, coś się kończy, coś się zaczyna i tak Projekt CODE, a wraz z nim X-Forum, kończą swoją działalność, by istnieć mogła całkiem nowa strona. Trochę szkoda, ale należy spojrzeć prawdzie w oczy i przyznać, że ta chwila musiała kiedyś nastąpić. Większość tekstów z Projektu przeniosłem jednakże tutaj, do działu Texts, a X-Forum ma być w przyszłości dostępne w postaci statycznego zrzutu wszystkich tematów.

Dość jednak o przeszłości! Patrzeć trzeba przed siebie! I co tam widzimy? No cóż… Kilka lat studiów, średnio płatna praca i śmierć… Tymczasem jednak będę się starał umieszczać od czasu do czasu jakieś nowe pliku lub artykuły na tej stronce, która nie jest już żadnym projektem dzięki czemu nie będzie mnie irytować, że od pól roku nie ma żadnej aktualizacji.

Na razie to tyle… Ja lecę liczyć całki.