Low res by default

Image Swap

Without Javascript

You can load low resolution images, but offer high resolution images too. This image swapper is a way to provide that feature without any javascript. It works because images that are display:none won't be loaded, and because we can use CSS and the :target selector as a very simple toggle mechanism.

Below I'll go into a description of what's happening here, but first the code.

The HTML

<html id='imghigh'>
		<body id="imglow'>
		<figure>
		  <a href="#imghigh" class="h">•</a>
		  <a href="#imglow" class="l">•</a>
		  <img class="high" 
		  	src="../assets/img/landscape.jpg" 
			alt="Landscape view" 
			loading="lazy" 
			width="1280" height="849">
		  <img class="low" 
		  	src="../assets/img/landscape-low.png" 
			alt="Landscape view" 
			loading="lazy" 
			width="500" height="331">
		</figure>
		</body>
		</html>

The CSS

.high {
		  display:none;
		}
		
		figure a {
		  position: absolute;
		  top: 40px;
		  left: 5px;
		  text-decoration: none;
		  color:#c13f00;
		  font-size:50px;
		}
		
		a.l {
		  display:none;
		}
		
		html:target .high,
		html:target a.l,
		body:target a.h {
		  display:block;
		}
		
		html:target .low,
		html:target a.h,
		body:target a.l{
		  display:none;
		}

Description

So we have two images, and we code them both in, but one is given the class .high which is display:none so it won't load by default. The image with class .low will load initially. There are two button/links as well. In my example, they are inside the figure, but they can be anywhere in the page. When a dot link is clicked it :targets either the HTML tag or the BODY tag. Really those IDs could be on any parent wrapper, using HTML and BODY is not required. Since the :target for #imghigh wraps everything, we can modify things with CSS. In the example above html:target means high-resolution image mode is active and body:target means low-resolution image mode is active. Those modes are used to hide both the appropriate button, and the appropriate image.

Check it out in action on the home and soon on the rest of this site.