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>View Transitions Demo: Accordion</h1>
<div class="box">
<p>This demo is a POC for <a href="https://github.com/w3c/csswg-drafts/issues/8320" target="_top">w3c/csswg-drafts#8320</a> and <a href="https://github.com/w3c/csswg-drafts/issues/9141" target="_top">w3c/csswg-drafts#9141</a>.<br>It contains a (rough) polyfill for CSS <code>attr()</code> and <code>ident()</code></p>
<p>Try this demo in Chrome Canary for best effect as it relies on <code>view-transition-class</code>.</p>
<p>Original demo for comparison: <a href="https://codepen.io/bramus/pen/xxmozvN" target="_top">https://codepen.io/bramus/pen/xxmozvN</a></p>
</div>
</header>
<main>
<div class="accordion">
<div class="item" id="item-1">
<input type="radio" name="accordion" value="unblur" id="unblur" checked />
<label for="unblur">
<span class="title">Photo Unblur fixes your pics, even the old ones.</span>
<span class="marker">›</span>
</label>
<div>
<h2>Photo Unblur fixes your pics, even the old ones.</h2>
<p>With a tap, sharpen and brighten picture-imperfect photos – even ones from non-Pixel phones. #FixedOnPixel</p>
</div>
</div>
<div class="item" id="item-2">
<input type="radio" name="accordion" value="magic-eraser" id="magic-eraser" />
<label for="magic-eraser">
<span class="title">Easily remove distractions in photos with Magic Eraser.</span>
<span class="marker">›</span>
</label>
<div>
<h2>Easily remove distractions in photos with Magic Eraser.</h2>
<p>Make unwanted objects or photobombers disappear. Or change the color and brightness so an object blends right in. #FixedOnPixel</p>
</div>
</div>
<div class="item" id="item-3">
<input type="radio" name="accordion" value="night-sight" id="night-sight" />
<label for="night-sight">
<span class="title">Details pop out in the dark with Night Sight.</span>
<span class="marker">›</span>
</label>
<div>
<h2>Details pop out in the dark with Night Sight.</h2>
<p>Now it’s easier to create rich, vibrant photos when it’s dark – city lights, portraits in low light, and starry skies with astrophotography.</p>
</div>
</div>
<div class="item" id="item-4">
<input type="radio" name="accordion" value="super-res-zoom" id="super-res-zoom" />
<label for="super-res-zoom">
<span class="title">Get amazing closeups with Super Res Zoom.</span>
<span class="marker">›</span>
</label>
<div>
<h2>Get amazing closeups with Super Res Zoom.</h2>
<p>The Pixel 7a camera includes Super Res Zoom. So you can get up close without an extra telephoto lens.</p>
</div>
</div>
<div class="item" id="item-5">
<input type="radio" name="accordion" value="long-exposure" id="long-exposure" />
<label for="long-exposure">
<span class="title">Create energetic photos with Long Exposure.</span>
<span class="marker">›</span>
</label>
<div>
<h2>Create energetic photos with Long Exposure.</h2>
<p>Add motion, texture, and artful blurs – including light trails – to waterfalls, crowds, city streets, and more. All without a tripod.</p>
</div>
</div>
</div>
</main>
<footer>
<p>Example URL: <a href="https://store.google.com/us/product/pixel_7a?hl=en-US">Pixel 7a – Google Store</a></p>
</footer>
@layer reset, layout, transitions;
body {
background: white;
}
@layer transitions {
:root {
view-transition-name: none;
}
.item {
--id: attr(id); /* Extract id from id attribute */
view-transition-name: _auto; /* Using _auto because the engine currently disallows `auto` */
view-transition-class: item;
.marker {
view-transition-name: _auto; /* Using _auto because the engine currently disallows `auto` */
view-transition-class: marker;
}
&:has(input:checked) {
& h2 {
view-transition-name: ident("title-" var(--id)); /* Dynamically construct ident using --id */
view-transition-class: title;
}
}
&:not(.item:has(input:checked)) {
& .title {
view-transition-name: ident("title-" var(--id)); /* Dynamically construct ident using --id */
view-transition-class: title;
}
}
}
@keyframes rotate-marker {
from {
rotate: 90deg;
}
to {
rotate: 270deg;
opacity: 0;
}
}
::view-transition-group(*) {
animation-duration: 0.5s;
}
::view-transition-group(.item) {
overflow: hidden;
}
::view-transition-old(.marker):only-child {
animation-name: rotate-marker;
}
::view-transition-new(.marker):only-child {
animation-name: rotate-marker;
animation-direction: reverse;
}
}
@layer layout {
@layer general {
body {
background: #efeae6;
font-family: 'Google Sans', Roboto, Arial, sans-serif;
padding-top: 3rem;
}
header,
footer {
text-align: center;
}
main {
margin: 2em auto;
width: 90%;
max-width: 30em;
}
.box {
border: 1px solid #a4a4a4;
width: max-content;
margin: 0 auto;
padding: 1em;
border-radius: 1em;
background: rgb(255 255 125 / 0.25);
> *:first-child { margin-top: 0; }
> *:last-child { margin-bottom: 0; }
}
a {
color: blue;
}
}
@layer accordion {
.accordion {
display: grid;
grid-auto-flow: row;
gap: 0.5em;
border-radius: 1em;
overflow: hidden;
font-size: 1.25em;
}
.item {
background: #f8f6f2;
display: flex;
flex-direction: column;
& input {
position: absolute;
opacity: 0;
}
& label {
flex: 1;
cursor: pointer;
padding: 1em;
display: flex;
flex-direction: row;
gap: 1em;
justify-content: space-between;
}
.marker {
display: grid;
place-content: center;
height: 1.5rem;
aspect-ratio: 1;
border-radius: 50%;
background-color: #fff;
color: #5f6368;
font-weight: 700;
font-size: 1.5em;
line-height: 1;
rotate: 90deg;
}
& div {
padding: 1em;
:first-child {
margin-top: 0;
}
:last-child {
margin-bottom: 0;
}
}
}
/* Show/Hide label/content based on input being checked or not */
.item:has(input:checked) {
& label {
display: none;
}
}
.item:not(.item:has(input:checked)) {
& div {
display: none;
}
}
}
}
@layer reset {
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
}
const randomBetween = (min, max) => {
return Math.random() * (max - min) + min;
}
document.querySelectorAll('.item input').forEach(($input) => {
// @note: we listen on click because that happens *before* a change event
$input.addEventListener('click', async (e) => {
if (!document.startViewTransition) return;
e.preventDefault();
const t = document.startViewTransition(() => {
e.target.setAttribute('checked', 'checked'); // Needed to trigger the Polyfill’s MutationObserver
e.target.checked = true; // Needed to actually update the checked input
});
await t.finished;
console.log('done');
});
});
class SelectorMatcher {
static watchers = new Map();
static matchedElements = new Map();
static observer;
static register({selector, onMatch, onUnmatch}) {
const watchers = this.watchers.has(selector) ? this.watchers.get(selector) : [];
watchers.push({
selector,
onMatch,
onUnmatch,
currentMatches: [],
});
this.watchers.set(selector, watchers);
}
static processWatchers = (selector, watchers) => {
const $newMatches = Array.from(document.querySelectorAll(selector));
const $oldMatches = this.matchedElements.has(selector) ? this.matchedElements.get(selector) : [];
// Process unmatches
for (const $oldMatch of $oldMatches) {
if (!$newMatches.includes($oldMatch)) {
for (const watcher of watchers) {
watcher.onUnmatch($oldMatch);
}
}
}
// Process matches
for (const $newMatch of $newMatches) {
if (!$oldMatches.includes($newMatch)) {
for (const watcher of watchers) {
watcher.onMatch($newMatch);
}
}
}
this.matchedElements.set(selector, $newMatches);
};
static watch() {
this.observer = new MutationObserver((mutationList, observer) => {
for (const mutation of mutationList) {
// console.log(mutation);
for (const [selector, watchersForSelector] of this.watchers.entries()) {
this.processWatchers(selector, watchersForSelector);
}
}
});
this.observer.observe(document.documentElement, { attributes: true, childList: true, subtree: true });
// @TODO: Watch clicks, hovers, focus, etc.
}
static unwatch() {
this.observer?.disconnect();
}
};
class StyleSheetProcessor {
static properties = [];
static valueRewriter = null;
static process = (styleSheets, properties, valueRewriter) => {
this.properties = properties;
this.valueRewriter = valueRewriter;
for (const styleSheet of styleSheets) {
this.processStyleSheet(styleSheet);
}
}
static processStyleSheet = (styleSheet) => {
this.processCSSRules(styleSheet.cssRules);
};
static processCSSRules = (cssRules) => {
if (cssRules) {
for (const cssRule of cssRules) {
this.processCSSRule(cssRule);
}
}
};
static processCSSRule = (cssRule) => {
// Process Style Decelaration
this.processCSSStyle(cssRule.styleMap, cssRule.style);
// Process Nested Rules
this.processCSSRules(cssRule.cssRules);
};
static processCSSStyle = (stylePropertyMap, styleDeclaration) => {
if (stylePropertyMap) {
for (const [prop, val] of stylePropertyMap) {
if (this.properties.includes(prop)) {
// Extract (flattened) selector from rule
const selector = this.resolveSelector(styleDeclaration.parentRule);
const createMatcher = (property, value) => {
return ($element) => {
$element.style.setProperty(
property,
this.valueRewriter(
value,
$element
)
);
}
};
const createUnmatcher = (property) => {
return ($element) => {
$element.style.setProperty(property, '');
}
};
// Register a SelectorMatcher watcher
SelectorMatcher.register({
selector,
onMatch: createMatcher(prop, styleDeclaration.getPropertyValue(prop)),
onUnmatch: createUnmatcher(prop),
});
// Remove the original declaration from the stylePropertyMap
stylePropertyMap.delete(prop);
}
}
}
};
static resolveSelector = (cssRule) => {
let selector = '';
const selectorTexts = [];
do {
if (cssRule.selectorText) {
selectorTexts.unshift(cssRule.selectorText);
}
cssRule = cssRule.parentRule;
} while (cssRule);
for (let selectorText of selectorTexts) {
// This is not needed, as CSSOM already prepends the & for nested selectors
// if (!selectorText.includes('&')) {
// selectorText = `& ${selectorText}`;
// }
selector = selectorText.replaceAll('&', `:is(${selector})`);
}
return selector;
};
}
console.clear();
const polyfill = () => {
// Properties to check
const properties = ['--id', 'view-transition-name'];
// Core of the polyfill that can rewrite CSS property values
// @TODO: This needs proper value parsing, but hey … it’s a POC
const valueRewriter = (value, $element) => {
// auto
const isAuto = value.trim() === '_auto';
if (isAuto) {
const ident = `vt-${randomBetween(0, 32768).toFixed()}-${randomBetween(0, 32768).toFixed()}`;
return ident;
}
// attr()
const isAttr = /attr\((.*)\)/gm;
if (value.match(isAttr)) {
const attribute = isAttr.exec(value)[1];
if (['nonce'].includes(attribute)) {
throw new Error(`Reading the attribute “${attribute}” using attr() is not allowed`);
}
return $element.getAttribute(attribute);
}
// ident()
const isIdent = /ident\((.*)\)/gm;
if (value.match(isIdent)) {
let ident = isIdent.exec(value)[1];
// Replace all Custom Props first
const customProps = Array.from(ident.matchAll(/var\((.*?)\)/g));
for (const customProp of customProps) {
ident = ident.replaceAll(customProp[0], getComputedStyle($element).getPropertyValue(customProp[1]));
}
// TODO: One can use attr() here as well
// Glue it all together by removing quotes and whitespace
ident = ident.replaceAll(' ', '').replaceAll('"', '').replaceAll('\'', '');
return ident;
}
// Any other value
return value;
};
StyleSheetProcessor.process(document.styleSheets, properties, valueRewriter);
SelectorMatcher.watch();
}
console.clear();
polyfill();
Also see: Tab Triggers