HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<header>
<h1>Accessible <code style="white-space:nowrap;"><image-compare></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;"><image-compare <b>exposure="0"</b>></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><img></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 & wrapped in a <code><figure></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>
/* 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; }
}
}
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);
Also see: Tab Triggers