Charles Harries

| Stream

Fun w/ hsl pt. 2

I hinted at a fun way to use the CSS hsl() colour function in a recent post. Now you can see what I mean, in action!

In a recent post, I wrote a little bit about a bit of fun that you can have with the CSS hsl() colour function.

The effect of this is that you can do some nifty stuff, programmatically, like adjusting the colour based on the time of day—0 at midnight, 355 at 11:59, ticking slowly round the wheel as the hands travel around the clock.

Now you can see what I mean! This very website's colour scheme depends on the time of day—which is used to set the first argument to hsl(), dictating the colour based on how far through the day we are. At midnight, the website is red; in the morning it cycles to green, then through cyan at midday, blue in the afternoon, gradually fading back to red in the evening.

This website's colour scheme in the morning...
This website's colour scheme in the morning...
...and the colour scheme in the evening
...and the colour scheme in the evening

It's a fun effect, but more importantly, it doesn't take any JavaScript to run! The logic that determines the number is a simple Twig function:

function percentThroughDay($time = null)
{
	$start = strtotime("today");
	$end = strtotime("tomorrow");
	$now = time();
	if ($time) {
		$now = (new DateTime($time))->format('U');
	}
	$secondstoday = $end - $start;
	$secondselapsed = $now - $start;
	return $secondselapsed / $secondstoday;
}

Then I multiply that by 355 (the number of degrees in the colour wheel, 0-indexed) and set it as a CSS Custom Property on the <html> element:

<html style="--primary: {{ percentThroughDay() * 360 }}">

Harmless fun at almost no cost.

Web Design Code