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

              
                <a class="Top" id="top" href="#main">
  <span>skip to content</span>
</a>
<div class="Page">
  <header class="Header Header--sticky">
    <a target="_top" href="https://codepen.io/dbushell/full/xxmzddB"><b>Demo Website</b></a>
    <button popovertarget="nav" class="Hamburger">
      <span>Menu</span>
    </button>
  </header>
  <main class="Main" id="main">
    <h1>🍀 Off-Canvas Navigation ²</h1>
    <p><strong>WORK IN PROGRESS! This is very experimental and <u>not yet accessibility reviewed!</u></strong></p>
    <p>Last updated <em>2nd October 2023</em></p>
    <ul>
      <li>A rebuild of the <a target="_blank" href="https://codepen.io/dbushell/full/yLMEogE">original CodePen</a></li>
      <li>Core interactivity does not need JavaScript</li>
      <li>Handles focus state and keyboard navigation</li>
      <li>Uses CSS <b><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Popover_API">popover</a></b> for sub-menus</li>
      <li>Respects reduced motion preference</li>
      <li>Optional sticky / auto-hide header</li>
      <li><a href="#nav">Open navigation</a> from any link</li>
      <li>
        <label>
          <input type="checkbox" id="toggle-rtl" autocomplete="off">
          <span>Supports <abbr title="right-to-left">RTL</abbr> styles</span>
        </label>
      </li>
    </ul>
    <p><a target="_blank" href="https://dbushell.com/2021/06/17/css-off-canvas-responsive-navigation/">Read my original blog article for more information</a></p>
    <p>Feedback and comments: <a href="https://twitter.com/dbushell" target="_blank">@dbushell</a> and <a href="https://fosstodon.org/@dbushell" target="_blank">@dbushell@fosstodon.org</a></p>
    <h2>Possible issues</h2>
    <p><b>Firefox</b> as of version 118 requires a <a target="_blank" href="https://github.com/oddbird/popover-polyfill">polyfill</a> for <a target="_blank" href="https://caniuse.com/?search=popover">popover</a></p>
  </main>
  <footer class="Footer">
    <p>
      <small>
        <span>MIT licensed | Copyright © 2023</span>
        <span><a href="https://dbushell.com" target="_blank">David Bushell</a></span>
      </small>
    </p>
  </footer>
</div>
<!--/Page--->
<dialog popover class="Nav" id="nav">
  <nav class="Nav__body" aria-labelledby="nav-heading">
    <header class="Nav__header">
      <h2 class="Nav__heading" id="nav-heading">Menu</h2>
      <button popovertarget="nav" popovertargetaction="close" class="Hamburger">
        <span>Close</span>
      </button>
    </header>
    <ul class="Nav__menu" id="menu-0">
      <li class="Nav__item">
        <button popovertarget="menu-1" class="Nav__link">
          <span id="menu-1-heading">Sub Menu 1</span>
        </button>
        <ul popover class="Nav__menu" id="menu-1" aria-labelledby="menu-1-heading">
          <li class="Nav__item">
            <button popovertarget="menu-1" popovertargetaction="close" class="Nav__link">
              <span>Back</span>
              <span class="Hidden">to main menu</span>
            </button>
          </li>
          <li class="Nav__item">
            <button popovertarget="menu-3" class="Nav__link">
              <span id="menu-3-heading">Nested Sub Menu 3</span>
            </button>
            <ul popover class="Nav__menu" id="menu-3" aria-labelledby="menu-3-heading">
              <li class="Nav__item">
                <button popovertarget="menu-3" popovertargetaction="close" class="Nav__link">
                  <span>Back</span>
                  <span class="Hidden">to parent menu</span>
                </button>
              </li>
              <li class="Nav__item">
                <a href="#" class="Nav__link">Menu Item</a>
              </li>
              <li class="Nav__item">
                <a href="#" class="Nav__link">Menu Item</a>
              </li>
              <li class="Nav__item">
                <a href="#" class="Nav__link">Menu Item</a>
              </li>
            </ul>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
        </ul>
      </li>
      <li class="Nav__item">
        <button popovertarget="menu-2" class="Nav__link">
          <span id="menu-2-heading">Sub Menu 2</span>
        </button>
        <ul popover class="Nav__menu" id="menu-2" aria-labelledby="menu-2-heading">
          <li class="Nav__item">
            <button popovertarget="menu-2" popovertargetaction="close" class="Nav__link">
              <span>Back</span>
              <span class="Hidden">to main menu</span>
            </button>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
          <li class="Nav__item">
            <a href="#" class="Nav__link">Menu Item</a>
          </li>
        </ul>
      </li>
      <li class="Nav__item">
        <a href="#" class="Nav__link">Menu Item</a>
      </li>
    </ul>
  </nav>
  <!--/Nav__body-->
</dialog>
<!--/Nav-->

              
            
!

CSS

              
                @layer base, components, utilities;

@layer base {
  :root {
    --white: 100% 0 0;
    --light: 98% 0.02 85;
    --dark: 40% 0.02 18;
    --magenta: 67% 0.28 337;
    --header-opacity: 0;
    --header-visible: 1;
    --header-height: 3.75rem;
    --focus-outline-width: 0.125rem;
    --nav-width: clamp(0rem, 100dvw, 25rem);
    --nav-dir: 1;
    scrollbar-gutter: stable;

    &[dir='rtl'] {
      --nav-dir: -1;
    }
  }

  *,
  *::after,
  *::before {
    box-sizing: border-box;
  }

  html {
    background: oklch(var(--light));
    color: oklch(var(--dark));
    font-family: 'Raleway', sans-serif;
  }

  .translated-rtl {
    direction: rtl;
  }

  body {
    margin: 0;
    min-height: 100dvh;
    padding: 0;
  }

  a[href],
  button,
  [tabindex='-1'] {
    color: currentColor;
    transition: color 200ms ease;

    &:focus {
      outline: none;
    }

    &:focus-visible {
      outline: var(--focus-outline-width) solid oklch(var(--magenta));
    }

    &:hover {
      color: oklch(var(--magenta));
    }
  }

  img {
    border: 0;
    display: block;
    height: auto;
    max-width: 100%;
  }

  button {
    background: transparent;
    appearance: none;
    border: none;
    outline: none;

    &:hover {
      cursor: pointer;
    }
  }
}

@keyframes nav-open {
  from {
    transform: translateX(calc(var(--nav-dir) * var(--nav-width)));
  }
  to {
    transform: translateZ(0);
  }
}

@keyframes nav-close {
  from {
    transform: translateZ(0);
  }
  to {
    transform: translateX(calc(var(--nav-dir) * var(--nav-width)));
  }
}

@keyframes nav-backdrop-open {
  from {
    background: rgb(0, 0, 0, 0);
  }
  to {
    background: rgb(0, 0, 0, 0.2);
  }
}

@keyframes nav-backdrop-close {
  from {
    background: rgb(0, 0, 0, 0.2);
  }
  to {
    background: rgb(0, 0, 0, 0);
  }
}

@layer components {
  .Top {
    align-items: center;
    background: oklch(var(--white));
    display: flex;
    height: var(--header-height);
    outline-offset: calc(-2 * var(--focus-outline-width));
    padding: 0.5rem 1rem;
    position: absolute;
    z-index: 10000;
    
    &:not(:focus) {
      clip: rect(0 0 0 0);
      clip-path: inset(50%);
      height: 1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1px;
      white-space: nowrap;
    }
  }

  .Header {
    align-items: center;
    background: oklch(var(--white) / var(--header-opacity));
    display: flex;
    height: var(--header-height);
    justify-content: space-between;
    padding: 0.5rem 1rem;
  }

  .Header--sticky {
    position: sticky;
    top: 0;

    :where(.Script) & {
      transform: translateY(calc((1 - var(--header-visible)) * -100%));
      transition: transform 300ms linear 100ms;
    }
  }

  .Nav {
    background: transparent;
    border: 0;
    height: 100%;
    margin: 0;
    overflow: hidden;
    padding: 0;
    max-height: none;
    max-width: none;
    width: 100%;

    &::backdrop {
      background: rgb(0, 0, 0, 0.2);
    }

    &[open] {
      animation: nav-open 500ms ease;

      &::backdrop {
        animation: nav-backdrop-open 500ms ease;
      }
    }

    &.nav-close {
      animation: nav-close 500ms ease;

      &::backdrop {
        animation: nav-backdrop-close 500ms ease;
      }
    }
  }

  .Nav__body {
    background: oklch(var(--white));
    box-shadow: 0 0 2rem rgb(0, 0, 0, 0.2);
    inset: 0;
    inset-inline-start: auto;
    height: 100%;
    max-width: var(--nav-width);
    position: absolute;
    pointer-events: none;
    width: 100%;

    & > * {
      min-width: 0;
      pointer-events: auto;
    }
  }

  .Nav__header {
    align-items: center;
    background: oklch(var(--white));
    display: flex;
    flex-shrink: 0;
    height: var(--header-height);
    justify-content: space-between;
    padding: 0.5rem 1rem;
    position: sticky;
    top: 0;
  }

  .Nav__heading {
    font-size: 1rem;
    margin: 0;
  }

  .Nav__menu {
    background: oklch(var(--white));
    border: 0;
    height: auto;
    inset: 0;
    inset-inline-start: auto;
    list-style: none;
    margin: 0;
    margin-block-start: var(--header-height);
    max-width: var(--nav-width);
    min-height: calc(100dvh - var(--header-height));
    overflow-x: hidden;
    overflow-y: auto;
    padding: 0.5rem;
    position: fixed;
    pointer-events: auto;
    width: 100%;
    -webkit-overflow-scrolling: touch;

    &:popover-open {
      animation: nav-open 500ms ease;
    }

    &.popover-close {
      animation: nav-close 500ms ease;
    }

    .nav-close &[popover] {
      animation: nav-close 500ms ease;
    }
  }

  .Nav__item {
    margin: 0;

    &:not(:last-of-type) {
      border-bottom: 0.0625rem solid black;
    }
  }

  .Nav__link {
    align-items: center;
    border-radius: 0.125rem;
    display: block;
    font-size: 1rem;
    font-weight: 400;
    padding: 0.5rem;
    text-decoration: none;
    line-height: 1.5;
    text-align: start;
    width: 100%;
  }

  .Hamburger {
    align-items: center;
    background: oklch(var(--magenta));
    border-radius: 0.625rem;
    color: oklch(var(--white));
    display: flex;
    outline-offset: 0.125rem;
    padding: 0.5rem 0.75rem;
    text-decoration: none;
    font-size: 1rem;
    justify-content: center;
    font-weight: 700;
    line-height: 1.5;
    text-align: center;
  }

  .Main,
  .Footer {
    --padding: clamp(1rem, 5dvw, 3rem);
    margin: 0 auto;
    max-width: calc(75rem + 10dvw);
    padding: var(--padding);
    width: 100%;

    & > *:first-child {
      margin-block-start: 0;
    }

    & + & {
      padding-block-start: 0;
    }

    & > h1,
    & > h2,
    & > h3 {
      line-height: 1.25;
      margin-block: 1.5rem 1rem;
    }

    & > ul {
      margin-block: 1.5rem;
      padding-inline: 2rem 0;

      & li {
        margin-block: 0.5rem;
      }
    }

    & > p {
      margin-block: 1rem;
    }
  }
}

@layer utilities {
  .Hidden {
    border: 0;
    clip: rect(0 0 0 0);
    clip-path: inset(50%);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
    white-space: nowrap;
  }
}

@media (prefers-reduced-motion) {
  .Nav,
  .Nav *,
  .Header {
    animation: none;
    transition: none;
  }
}

              
            
!

JS

              
                (() => {
  // Respect user perference
  const isReducedMotion = window.matchMedia(
    '(prefers-reduced-motion: reduce)'
  ).matches;

  const $nav = document.querySelector('.Nav');
  const $links = [...$nav.querySelectorAll('.Nav__link')];
  const $popovers = [...$nav.querySelectorAll('[popover]')];

  const $toggles = new Set([
    ...document.querySelectorAll('[popovertarget="nav"]'),
    ...document.querySelectorAll('[href="#nav"]')
  ]);

  $nav.addEventListener('click', (ev) => {
    // Close nav when clicking outside
    if (ev.target === $nav) {
      closeNav();
      return;
    }
    // Play closing animation before popover is hidden
    const $button = ev.target.closest('[popovertargetaction="close"]');
    if ($button && !isReducedMotion) {
      ev.preventDefault();
      const $popover = $button.closest('[popover]');
      $popover.classList.add('popover-close');
      $popover.addEventListener('animationend', () => {
          $popover.classList.remove('popover-close');
          $popover.hidePopover();
        },
        {once: true}
      );
    }
  });

  $popovers.forEach(($popover) => {
    $popover.addEventListener('toggle', (ev) => {
      if (ev.target !== $popover) {
        return;
      }
      // Ensure hidden links are not focusable
      $links.forEach(($link) => {
        $link.tabIndex = $link
          .closest('[popover]')
          ?.querySelector(':popover-open')
          ? -1
          : 0;
      });
      if (ev.newState === 'open') {
        // Focus first button or link
        $popover.querySelector('button,[href]')?.focus();
      }
      if (ev.newState === 'closed') {
        // Return focus to parent toggle
        $popover.parentNode
          .querySelector(`[popovertarget="${$popover.id}"]`)
          ?.focus();
      }
    });
  });
  
  const openNav = () => {
    document.body.style.overflow = 'hidden';
    $nav.showModal();
  };

  const closeNav = () => {
    document.body.style.removeProperty('overflow');
    if (isReducedMotion) {
      $nav.close();
      return;
    }
    // Play animation before dialog is closed
    $nav.classList.add('nav-close');
    $nav.addEventListener('animationend', () => {
        $nav.classList.remove('nav-close');
        $nav.close();
      },
      {once: true}
    );
  };
  
  const toggleNav = () => ($nav.open ? closeNav() : openNav());

  $nav.addEventListener('cancel', (ev) => {
    ev.preventDefault();
    closeNav();
  });

  $nav.addEventListener('close', () => {
    // Ensure all nested popovers are reset
    $popovers.forEach(($popover) => $popover.hidePopover());
  });

  $toggles.forEach(($toggle) => {
    $toggle.addEventListener('click', (ev) => {
      ev.preventDefault();
      ev.stopImmediatePropagation();
      toggleNav();
    });
  });
})();


// Optional sticky header
(() => {
  const $top = document.querySelector('.Top');
  const $header = document.querySelector('.Header--sticky');

  if ($header) {
    let observeFrame;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (observeFrame) {
            window.cancelAnimationFrame(observeFrame);
          }
          observeFrame = window.requestAnimationFrame(() => {
            $header.style.setProperty(
              '--header-opacity',
              1 - entry.intersectionRatio
            );
          });
        });
      },
      {threshold: [...Array(101).keys()].map((x) => x / 100)}
    );
    observer.observe($top);

    let wScrollFrame;
    let wScrollOffset = $top.offsetHeight;
    let wScrollY = window.scrollY;

    const onWindowScrollQueue = [
      () => {
        const scrollY = window.scrollY;
        if (scrollY > wScrollOffset) {
          $header.style.setProperty(
            '--header-visible',
            scrollY > wScrollY ? 0 : 1
          );
        }
        wScrollY = scrollY;
      }
    ];

    window.addEventListener(
      'scroll',
      () => {
        if (wScrollFrame) {
          window.cancelAnimationFrame(wScrollFrame);
        }
        wScrollFrame = window.requestAnimationFrame(() =>
          onWindowScrollQueue.forEach((fn) => fn())
        );
      },
      {passive: true}
    );
  }
})();



(() => {
  // Toggle right-to-left for demo purposes
  document.querySelector('#toggle-rtl')?.addEventListener('change', (ev) => {
    document.dir = ev.target.checked ? 'rtl' : 'ltr';
  });
  // https://github.com/oddbird/popover-polyfill
  if (!('popover' in HTMLElement.prototype)) {
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/@oddbird/popover-polyfill@latest';
    script.crossOrigin = 'anonymous';
    script.defer = true;
    document.head.appendChild(script);
    const style = document.createElement('style');
    style.innerHTML = `
[popover] {
  position: fixed;
  z-index: 2147483647;
}

[popover]:not(.\\:popover-open) {
  display: none;
}

[popover]:is(dialog[open]) {
  display: revert;
}

[anchor].\\:popover-open {
  inset: auto;
}

@supports selector([popover]:popover-open) {
  [popover]:not(.\\:popover-open, dialog[open]) {
    display: revert;
  }

  [anchor]:is(:popover-open) {
    inset: auto;
  }
}
    `;
    document.head.appendChild(style);
  }
})();

              
            
!
999px

Console