<main>
<div class="wrapper">
<article class="flow">
<h1>Grid stacking and <code>z-index</code></h1>
<figure class="callout">
<p>Toggle item one’s <code>z-index</code> to see how it affects stacking.</p>
</figure>
<div class="controls">
<label class="toggle" for="z-index">
<span class="toggle__label">Switch “item one” to have a <code>z-index</code> of 2</span>
<input type="checkbox" role="switch" class="toggle__element" id="z-index">
<div class="toggle__decor" aria-hidden="true">
<div class="toggle__thumb"></div>
</div>
</label>
</div>
<div class="container" id="container">
<div class="box bg-primary color-light">Item one</div>
<div class="box">Item two</div>
<div class="box">Item three has more text </div>
<div class="box">Item four</div>
<div class="box">Item five</div>
</div>
</article>
</div>
</main>
:root {
--var-z-index: 0;
}
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-auto-rows: minmax(100px, auto);
grid-auto-flow: var(--var-packing);
gap: 10px;
background-color: #dadce0;
padding: .5em;
border-radius: 3px;
max-inline-size: 500px;
}
.box {
z-index: 0;
}
.box:nth-child(1) {
grid-row: 1 / 4;
grid-column: 1;
z-index: var(--var-z-index);
}
.box:nth-child(2) {
grid-row: 1 / 3;
grid-column: 1 / -1;
}
.box:nth-child(3) {
grid-row: 2 / 4;
grid-column: 2 / -1;
}
let root = document.documentElement;
let zIndex = document.getElementById("z-index");
zIndex.addEventListener("click", function (evt) {
if(zIndex.checked) {
root.style.setProperty('--var-z-index', 2);
} else {
root.style.setProperty('--var-z-index', 0);
}
});
This Pen doesn't use any external JavaScript resources.