Search code examples
csssveltestickysveltekit

Why does CSS sticky not work (Sveltekit + UnoCSS)?


I have a Sveltekit project setup with UnoCSS, using the wind preset. Here's a glance at the code:

<!-- +layout.svelte -->

<script lang="ts">
  import 'uno.css';
  import '@unocss/reset/tailwind-compat.css';

  import '@fontsource/inter/400.css';
  import '@fontsource/inter/500.css';
  import '@fontsource/inter/600.css';

  import '../app.css';

  import Header from '$lib/Header.svelte';
</script>

<div
  class="min-h-screen px-6 text-white bg-black md:px-12 lg:px-24 xl:px-48 h-200vh"
>
  <Header />
  <slot />
</div>

<!-- +page.svelte -->

<main class="sticky flex flex-col justify-center h-screen py-20">
  <h1 class="text-9xl font-500 ui-head mt-1/17">
    I'm a <span class="ui-head">fullstack software engineer</span>,
    <span class="ui-head">musician</span>, &
    <span class="ui-head">minecrafter</span>.
  </h1>
  <p class="pb-4 mt-auto text-lg font-500 ui-head text-neutral-400">
    Keep Scrolling
  </p>
  <a
    href="#software-engineer"
    class="hidden gap-3 p-4 mt-auto text-black bg-white rounded-full hover:flex group w-fit"
  >
    <svg
      fill="none"
      stroke="currentColor"
      stroke-width="1.5"
      viewBox="0 0 24 24"
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden="true"
      class="w-1.8rem h-1.8rem"
    >
      <path
        stroke-linecap="round"
        stroke-linejoin="round"
        d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3"
      />
    </svg>
  </a>
</main>

<!-- Header.svelte -->

<header class="fixed z-50 flex items-center justify-between py-6 w-1467px bg-black bg-opacity-96%">
  <a href="/" class="text-1.3rem font-500 ui-head group"
    >quantasium<span class="absolute hidden text-neutral-300 group-hover:inline"
      >#0017</span
    ></a
  >
  <svg
    xmlns="http://www.w3.org/2000/svg"
    class="w-6.5 h-6.5 text-white cursor-pointer"
    viewBox="0 0 16 16"
    ><path
      fill="currentColor"
      d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z"
    /></svg
  >
</header>

The overarching <div></div> has the h-200vh style and has overflow shown. The <main></main> element is sticky. However, the sticky seems to have no effect, and the page scrolls normally. How can I fix this?


Solution

  • position: sticky; requires one of top, bottom, right, or left set. If you want it to stick to the top when you scroll down, set top: 0;