<!--
Emmet abbreviation:
input.image-loader[type='checkbox' aria-label='Load image of...']+img[loading='lazy' src='' alt='' width='' height='']
-->
<div style='width: 573px; height: 382px;'>
<input type='checkbox'
class='image-loader'
aria-label='Load image of hot air balloons over a misty landscape with a mountain in the background'>
<img loading='lazy'
src='https://assets.codepen.io/14179/musab-al-rawahi-KsfH7IYFn98-unsplash.jpg'
alt='Hot air balloons over a misty landscape with a mountain in the background'
width='573' height='382'>
</div>
<div style='width: 573px; height: 382px;'>
<input type='checkbox'
class='image-loader'
aria-label='Load image of hot air balloons over a misty landscape with a mountain in the background'>
<img loading='lazy'
src='https://assets.codepen.io/14179/musab-al-rawahi-KsfH7IYFn98-unsplash.jpg'
alt='Hot air balloons over a misty landscape with a mountain in the background'
width='573' height='382'>
</div>
/* Checkbox */
.image-loader {
appearance: none;
cursor: pointer;
outline: none;
}
.image-loader::before {
border: 1px solid #09577B;
border-radius: 3px;
color: #09577B;
content: attr(aria-label);
display: inline-block;
outline: none;
padding: 5px 10px;
transition: .25s ease-in-out;
transition-property: background, color;
}
.image-loader::after {
/*
Set width and height to match image
placeholder size if all images to be
loaded are the same size.
You could also make use of `aspect-ratio`
if all images have the same aspect ratio.
This prevents significant layout shift
without requiring a wrapper div.
*/
/*
content: '';
display: inline-block;
height: 382px;
position: relative;
width: 573px;
*/
}
.image-loader:hover::before,
.image-loader:focus::before {
background: #09577B;
color: #fff;
}
.image-loader:checked {
display: none;
}
/* Image */
/*
Using `display: none` stops the image
being loaded and allows native lazy loading
to take place.
Using `opacity: 0` and/or `visibility: hidden`,
and/or `position: absolute; left: -9999px; top: -9999px`
still loads the image on page load (tested).
The drawback is significant layout shift.
See the comment above for ONE workaround to this.
One of several alternative workarounds, and the one implemented here,
would be to wrap the checkbox and image in a container that has width/height
set to the image width/height.
In production, this would require server side access to the image's
width/height, such as that provided by virtually every CMS.
*/
.image-loader + img {
display: none;
height: auto;
width: 100%;
}
.image-loader:checked + img {
display: initial;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.