Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <header>
	<h1>Accessible <code style="white-space:nowrap;">&lt;image-compare&gt;</code> <span>Web Component</span> <small>(no Shadow DOM)</small></h1>
	<ul>
		<li>Using Light DOM allows you to style everything with regular CSS</li>
		<li>Horizontally scrollable container used as fallback if JS doesn't load (this also helps reduce CLS by stabilizing the overall height)</li>
		<li>No dependencies</li>
		<li><a href="https://github.com/nonsalant/image-compare" target="_parent">View on Github</a> (code organized into separate files)</li>
	</ul>
	<hr>
	<blockquote>
		Control how much of the first image is shown initially by adding an exposure attribute (0-100).
		<br>
		<small>
			<i>E.g:</i> <code style="font-size:1.2em;">&lt;image-compare <b>exposure="0"</b>&gt;</code> will hide the first image, a value of 100 will hide the second image, and a value of 50 will show half of each.
		</small>
	</blockquote>
	<hr>
</header>

<h2>Example 1: Just two <code>&lt;img&gt;</code> tags</h2>

<image-compare>
	<img alt="Alt text" src="https://assets.codepen.io/8247/Screenshot+2024-12-26+at+04.11.10.jpg" width="3584" height="2240" />
	<img alt="Alt text" src="https://assets.codepen.io/8247/Screenshot+2024-12-26+at+04.11.01.jpg" width="3584" height="2240" />
</image-compare>

<h2>Example 2: With a caption &amp; wrapped in a <code>&lt;figure&gt;</code></h2>

<figure>
	<image-compare>
		<img alt="Alt text" src="https://images.unsplash.com/photo-1548840566-8179dfe68157?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE3MzQ5MTE0Mjd8&ixlib=rb-4.0.3&q=85" />
		<img alt="Alt text" src="https://images.unsplash.com/photo-1646174050199-f6f9b32bd2f7?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE3MzQ5MTE0Mjd8&ixlib=rb-4.0.3&q=85" />
	</image-compare>
	<figcaption>Before/After</figcaption>
</figure>

<footer>
	<div style="display: flex; align-items: center; gap: 1rem; border: dotted 1px; margin-block: 1.5rem; padding: .5rem 1rem;">
		<h5 style="text-align: center; min-width: fit-content;">Too much CSS?</h5>
		<p><a href="https://codepen.io/nonsalant/pen/pvzrzdM" target="_parent" title="Opens in the parent frame" style="text-decoration:underline">Try this version</a> where non-critical CSS is moved to JS and made more DRY.</p>
	</div>
	<ul>
		<li>Forked from: <a target="_blank" href="https://cloudfour.com/thinks/building-an-accessible-image-comparison-web-component/">image-compare</a> by Paul Hebert for Cloud Four, which <a href="https://github.com/cloudfour/image-compare/blob/main/src/index.js" target="_blank">uses the Shadow DOM</a>.
		</li>
		<li>Inspired by this article: <a target="_blank" href="https://frontendmasters.com/blog/light-dom-only/#you-can-augment-or-replace-the-html-with-whatever">Light-DOM-Only Web Components are Sweet</a> by Chris Coyier.</li>
	</ul>
</footer>
              
            
!

CSS

              
                /* Remove default margin if nested in a figure */
figure:has(image-compare) { margin-inline: 0; }

image-compare {
	& {
		--exposure: 50%;
		--thumb-background-color: hsla(0, 0%, 100%, 0.9);
		--thumb-background-image: url('data:image/svg+xml;utf8,<svg viewbox="0 0 60 60" width="60" height="60" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="4" d="M20 20 L10 30 L20 40"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="4" d="M40 20 L50 30 L40 40"/></svg>');
		--thumb-size: clamp(3em, 10vmin, 5em);
		--thumb-radius: 50%;
		--thumb-border-color: hsla(0, 0%, 0%, 0.9);
		--thumb-border-size: 2px;
		--focus-width: var(--thumb-border-size);
		--focus-color: hsl(200, 100%, 80%);
		--divider-width: 2px;
		--divider-color: hsla(0, 0%, 0%, 0.9);
	}
	& {
		position: relative;
		display: flex;
		width: fit-content;
		max-width: 100%;
		margin-inline: auto;
		img { width: 100%; height: auto; }
		label {
			position: absolute;
			inset: 0;
			display: flex;
			align-items: stretch;
		}
		[type=range] {
			cursor: col-resize;
			appearance: none;
			-webkit-appearance: none;
			background: none;
			border: none;
			margin: 0 calc(var(--thumb-size) / -2);
			width: calc(100% + var(--thumb-size));
			height: unset;
		}
		/* Styling range inputs requires separately defining the CSS rules for -moz and -webkit. */
		/* ! bug in Safari when trying to nest -moz and -webkit together under the same [type=range] */
		[type=range] {
			&::-moz-range-track { height: unset; background: transparent; }
			&::-moz-range-thumb {
				background-color: var(--thumb-background-color);
				background-image: var(--thumb-background-image);
				background-size: 90%;
				background-position: center center;
				background-repeat: no-repeat;
				border-radius: var(--thumb-radius);
				border: var(--thumb-border-size) var(--thumb-border-color) solid;
				color: var(--thumb-border-color);
				width: var(--thumb-size);
				height: var(--thumb-size);
				margin: 0;
			}
			&:focus::-moz-range-thumb { box-shadow: 0px 0px 0px var(--focus-width) var(--focus-color); }
		}
		[type=range] {
			&::-webkit-slider-runnable-track { height: unset; background: transparent; }
			&::-webkit-slider-thumb {
				-webkit-appearance: none;
				background-color: var(--thumb-background-color);
				background-image: var(--thumb-background-image);
				background-size: 90%;
				background-position: center center;
				background-repeat: no-repeat;
				border-radius: var(--thumb-radius);
				border: var(--thumb-border-size) var(--thumb-border-color) solid;
				color: var(--thumb-border-color);
				width: var(--thumb-size);
				height: var(--thumb-size);
				margin: 0;
			}
			&:focus::-webkit-slider-thumb { box-shadow: 0px 0px 0px var(--focus-width) var(--focus-color); }
		}
	}
	&:not(:defined) {
		flex-direction: row;
		overflow-x: auto;
	}
	&:defined {
		flex-direction: column;
		overflow: clip;
		.image-2-wrapper {
			position: absolute;
			top: 0;
			/* shadow used for vertiacal divider */
			filter: drop-shadow( calc(-1*var(--divider-width)) 0 0 var(--divider-color) );
			img {
				--_top-left: calc(var(--exposure) + var(--divider-width)/2);
				--_bottom-left: calc(var(--exposure) + var(--divider-width)/2);
				clip-path: polygon(var(--_top-left) 0, 100% 0, 100% 100%, var(--_bottom-left) 100%);
			}
		}
	}
	/* adjecent figcaption */
	& + figcaption { 
		text-align: center; 
		margin-block-start: .5lh; 
	}
	/* utils */
	.visually-hidden {
		position: absolute;
		width: 1px; height: 1px;
		padding: 0; margin: -1px;
		overflow: hidden;
		clip: rect(0, 0, 0, 0);
		white-space: nowrap; /* added line */
		border: 0;
	}
}

/* You probably don't need the styles below */
@layer reset {
	*, *:before, *:after { box-sizing: border-box; }
/* 	img { display: block; max-width: 100%; height: auto; } */
}
@layer demo {
	html { color-scheme: light dark; }
	body {
		font-family: system-ui;
		font-family: 'SF Pro Text', 'SF Pro Icons', 'AOS Icons', 'Helvetica Neue', Helvetica, Arial, sans-serif, system-ui;
		text-wrap: balance;
		text-wrap: pretty;
		line-height: 1.4;
		padding-inline: 1lh;
		max-width: 45rem;
		margin-inline: auto;
	}
	a {
		color: inherit; font-weight: bold;
		text-decoration: none;
		&:hover { text-decoration: underline; }
	}
}
              
            
!

JS

              
                class ImageCompare extends HTMLElement {
	
	defaultExposure = 50;
	exposure = this.getAttribute('exposure') || this.defaultExposure;
	inputSelector = 'input[type=range]';
	secondImg = this.querySelectorAll('img')[1];
	
	/**
	* Generates an HTML string for a `<label>` containing a visually hidden
	* description for screen readers and an `<input type="range">` slider 
	* for setting the exposure value.
	*/
	ui(exposure) { 
		return `
		<label>
			<span class="visually-hidden">
				Control how much of each overlapping image is shown.
				0 means the first image is completely hidden.
				100 means the first image is fully visible.
				50 means both images are half-shown, half-hidden.
			</span>
			<input type="range" value="${exposure}" min="0" max="100" />
		</label>`;
	}
	
	constructor() { super(); }

	connectedCallback() {
		// setTimeout(() => {
			this.#setPropPercentage('--exposure', this.defaultExposure);
			this.#wrapSecondImg('span', 'image-2-wrapper');
			this.#appendHtml(this.ui(this.exposure));
			this.#setupInputListener(this.inputSelector);
		// });
	}

	static get observedAttributes() { return ['exposure']; }

	attributeChangedCallback(name, oldValue, newValue) {
		if (name === 'exposure') {
				const rangeInput = this.querySelector(this.inputSelector);
				if (rangeInput) {
						rangeInput.value = newValue;
						this.#setPropPercentage('--exposure', newValue);
				}
		}
	}

	#setupInputListener(el) {
		const rangeInput = this.querySelector(el);
		const handleInputChange = () => {
			this.setAttribute('exposure', rangeInput.value);
		};
		rangeInput.addEventListener('input', handleInputChange);
		rangeInput.addEventListener('change', handleInputChange);
	}

	#appendHtml(rawHtml) {
		const tempDiv = document.createElement('div');
		tempDiv.innerHTML = rawHtml;
		while (tempDiv.firstChild) {
			this.appendChild(tempDiv.firstChild);
		}
	}
	
	#wrapSecondImg(tag, className) {
		this.wrap(this.secondImg, tag, className);
	}
	
	#setPropPercentage(prop, value) {
		this.style.setProperty(prop, value + '%');
	}
	
	wrap(el, tag, className) {
		const wrapper = Object.assign(
			document.createElement(tag), {
				className: className
			}
		);
		el.parentNode.insertBefore(wrapper, el);
		wrapper.appendChild(el);
	}
	
}

customElements.define('image-compare', ImageCompare);

              
            
!
999px

Console