Creating a sticky section with Tailwind CSS utility classes

I have a page in my Next.js web app, and I want to make the section highlighted in blue (wrapped in <aside> tag) sticky so that it stays in place while scrolling, with only the main section containing the chart scrolling.

The code snippet below is from the layout.tsx file:

import { dashboardConfig } from "@/config/dashboard";
import { MainNav } from "@/components/nav/main-nav";
import { DashboardNav } from "@/components/nav/dashboard-nav";

interface DashboardLayoutProps {
  children?: React.ReactNode;
}

export default async function DashboardLayout({
  children,
}: DashboardLayoutProps) {
  return (
    <div className="flex min-h-dvh flex-col relative">
      <header className="container z-40 bg-background">
        <MainNav />
      </header>
      <div className="container grid flex-1 gap-12 md:grid-cols-[200px_1fr] mt-32 mb-12 relative">
        <aside className="hidden w-[200px] flex-col md:flex sticky top-0">
          <DashboardNav items={dashboardConfig.sidebarNav} />
        </aside>
        <main className="flex w-full flex-1 flex-col overflow-hidden">
          {children}
        </main>
      </div>
    </div>
  );
}

Even after applying the classes sticky and top-0, the desired sticky behavior is not working. What could be the issue?

Answer №1

One way to achieve a sticky effect for an element is by applying align-self: start using self-start. By default, the element would stretch to match the full height of its parent grid element, resulting in no sticky effect being visible. But when you apply align-self: start, the element will only be as tall as its content, thus allowing the sticky effect to work properly if there is vertical free space available.

const dashboardConfig = { sidebarNav: '' };
const MainNav = () => 'MainNav';
const DashboardNav = () => 'DashboardNav';

function DashboardLayout({
  children,
}) {
  return (
    <div className="flex min-h-dvh flex-col relative">
      <header className="container z-40 bg-background">
        <MainNav />
      </header>
      <div className="container grid flex-1 gap-12 md:grid-cols-[200px_1fr] mt-32 mb-12 relative">
        <aside className="hidden w-[200px] flex-col md:flex sticky top-0 self-start">
          <DashboardNav items={dashboardConfig.sidebarNav} />
        </aside>
        <main className="flex w-full flex-1 flex-col overflow-hidden">
          {children}
        </main>
      </div>
    </div>
  );
}

function App() {
  return (
    <DashboardLayout>
      <div class="h-[200vh]"></div>
    </DashboardLayout>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.tailwindcss.com/3.4.1"></script>

<div id="app"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How about utilizing React's conditional rendering feature?

I'm currently working on a component that displays tournaments and matches, and I'm facing a challenge in implementing a filter option for users to select tournaments by 'league', while still displaying all tournaments if no 'leagu ...

What is the best way to retrieve information from a local JSON file and store it in the state of

I am currently working on a project to develop a movies/series search app using Next.js and React based class components. I have successfully imported JSON content and displayed it using the map function as shown below: <div> {Appletv.shows.map(( ...

Adaptive Positioned Image Display

I currently have a Section with four blocks of content. Along the right-hand side of the screen, there are some images (as shown in this example) that I want to position absolutely. However, I am encountering an issue where these images overlap with the te ...

Issues detected with Foundation Block Grid in small size setting

I created a React component to display a series of div elements on a page using the Foundation Block Grid system to control the number of divs per row. However, I am facing an issue where the number of divs does not change when switching to a small-sized s ...

Utilizing MUI alongside Tailwind CSS in conjunction with NextJS: Here's a solution for resolving the transparent button issue without compromising the utilization of Tailwind CSS preflight

Currently working on a project built on top of a NextJS template using TailwindCSS. Struggling to integrate MUI components due to unexpected behavior with the button element (White Button error in NextJS Project). While I am aware of solutions suggesting ...

The system is unable to retrieve the value of the property which is set as null

I'm trying to figure out how to store the input value of name_enter into the variable userName. However, every time I attempt this, I encounter the following console error: Uncaught TypeError: Cannot read property 'value' of null function ...

Will inserting a * in a CSS file affect the styling in Internet Explorer?

I've been tasked with updating an older project to incorporate the latest technologies. Within the project's style sheets, some styles are prefixed with: #calendarDiv{ position:absolute; width:220px; *width:215px; *max-width:210px; border:1px s ...

Error occurred during NextJs deployment due to an issue with the getStaticPath function: An unexpected token "<" was found in the JSON at position 0 while trying to parse it

I've created this function to retrieve a path that will be used during local development mode. export async function getStaticPaths(){ const datas = await fetch(`https://mydomain.vercel.app/api/annonces/annonces`) const annonces = await datas. ...

I would like to mention a website without inserting a direct hyperlink, for example, in the Safari browser

Is there a way to prevent a website name from becoming a clickable link in Safari? In my marketing email, I am highlighting the websites of both my client and their competitor. When mentioning the competitor's site "sitename.com," I want to avoid cre ...

To create a complete layout without relying on fixed positioning, ensure that the header, container, and footer collectively

Is there a method to ensure the header, container, and footer encompass the entire layout without using fixed positioning in CSS? Check out this HTML fiddle for reference. <div class="wrapper"> <header> <img src="https://www.ecobin.co ...

Error encountered during Nuxt build: Syntax error on Line 1 of the SCSS component file

I'm currently working on a project in node 18.7.0 that utilizes nuxt 2.15.8. Within my Vue component, I have the following SCSS code: <style lang="scss"> .Accordion { --Accordion__margin-top: 2.5rem; &__items { margin ...

Tips for clearing floated images when the sidebar is also floated

Can someone assist me with this code snippet? I am trying to figure out a way to clear the nearest floated block. It seems that whenever I use the clear property, it clears any floated blocks on the page, even if they are in a different div. Here is the ...

Discover how to prevent a link or text from appearing if a user has already browsed a particular webpage

Is there a way to hide a link to another page if the user has previously visited that page? For example, I have 3 options - A, B, and C. If a user selects option A, links to pages B and C are displayed at the bottom of the page. However, if they then navi ...

Error: Unable to locate module: Issue: Unable to find '../components/charts/be.js' in '/vercel/workpath0/my-app/pages'

Having some trouble deploying my next.js app through Vercel. Everything works fine locally with the command 'npm run dev'. But when attempting to deploy it on Vercel using a Github remote repository, I encountered the following error: 18:07:58.29 ...

What is the best method for extracting the innerHTML value of html tags using a css selector or xpath?

I am currently struggling with retrieving the HTML inner text value using CSS selector or XPath. While I can achieve this using document.getElementById, I am unable to do so using selectors. I can only print the tag element but not the text from it. For e ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

The resizing of the background image is contingent upon the size of the

I am facing an issue with my bootstrap carousel. One of the items only contains a background image without any content. I have set a height for it so that it is still visible even without content. However, when viewing on mobile devices, I can only see a p ...

Tips for managing a 64-bit signed integer received from a NextJS backend API

I am currently developing a NextJS application in which one of the backend API routes sends back a JSON object that includes a 64-bit signed integer. // userID represents the 64-bit signed integer res.status(200).json({ id: userId, attributes: userAttribut ...

Step-by-step guide on creating a clickable button that triggers the appearance of a block showcasing a dimmed photo upon activation

Is there a way to create a button that triggers a pop-up block featuring a darkened photo when clicked? ...

JS will reach its stopping point at the specified style.zIndex

I am currently in the process of setting up button elements. I have two scripts that correspond to different types of buttons - one script runs a simple collapse menu, while the other executes a more complex collapse by shifting depths and sliding one div ...