<main>
      <div class="wrapper">
        <article class="flow">
          <h1>Relative positioning and z-index</h1>
          <figure class="callout">
            <p>
              Turn <code>position: relative;</code> off and on to see how it affects
              <code>z-index</code>.
            </p>
          </figure>
          <label class="toggle" for="toggle-element">
            <span class="toggle__label">Turn <code>position: relative;</code> on</span>
            <input
              type="checkbox"
              role="switch"
              class="toggle__element"
              id="toggle-element"
            />
            <div class="toggle__decor" aria-hidden="true">
              <div class="toggle__thumb"></div>
            </div>
          </label>
          <div class="demo">
            <div class="demo-box"><code>z-index: 3;</code></div>
            <div class="demo-box"><code>z-index: 1;</code></div>
            <div class="demo-box"><code>z-index: 2;</code></div>
          </div>
        </article>
      </div>
    </main>
.demo > * {
  width: 250px;
  height: 200px;
  padding: 1em;
}

.demo > [data-state='relative'] {
  position: relative;
  display: flex;
  flex-direction: column-reverse;
}

.demo > * + * {
  margin-top: -150px;
  opacity: 0.75;
  box-shadow: 0 -1px 10px rgba(0 0 0 / 60%);
}

.demo > :first-child {
  background: aliceblue;
  border: 2px solid lightblue;
  z-index: 3;
}

.demo > :nth-child(2) {
  background: pink;
  border: 2px solid hotpink;
  z-index: 1;
  margin-left: 1rem;
}

.demo > :last-child {
  background: wheat;
  border: 2px solid gold;
  z-index: 2;
}
const toggle = document.querySelector('#toggle-element');
const boxes = document.querySelectorAll('.demo-box');

toggle.addEventListener('change', ({target}) => {
  boxes.forEach(box =>
    box.setAttribute('data-state', target.checked ? 'relative' : 'static')
  );
});

External CSS

  1. https://codepen.io/web-dot-dev/pen/abpoXGZ.css

External JavaScript

This Pen doesn't use any external JavaScript resources.