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

Using shadow effects on the <Grid> component with Material UI

Is there a way to implement the box-shadow property on a <Grid> component in Material UI? I've gone through the official documentation regarding Shadows - Material UI, but I'm struggling to grasp how it can be applied to a <Grid>. De ...

Upgrading from Next.js version 10 to version 13: A Comprehensive Guide

Here is the content of my pages/my _app.js file: import { Provider } from 'next-auth/client'; import '../styles/globals.css'; import 'react-perfect-scrollbar/dist/css/styles.css'; import LayoutWrapper from '../components ...

Guide to deploying a Next JS App with Mongoose for MongoDB connectivity on Vercel

I am experiencing issues when trying to deploy my Next.js app on Vercel with a MongoDB connection. I have added environment variables on the Vercel site where we deploy the Next.js app. Is there anything wrong in the following file? next.config.js module. ...

The background image causes the scrollbar to vanish

As a beginner, I am in the process of creating a web page that features a consistent background image. However, I have encountered an issue where the scroll bar does not appear on a specific page called "family details" due to the background image. I atte ...

NEXT JS 13 experiencing an infinite loop when using State, encountering an error with Params, and facing issues with hook definition

Currently, I am in the process of developing a shopping cart using NEXT JS and encountering several issues within my code. To begin with, I have established a route [product]/[productitems] within the apps folder. In the page.tsx file of [productitems], I ...

Instructions for passing a JSX code-containing component as a prop to another component

I've developed a base component called Content.js, and instead of creating duplicates with slight modifications each time in my project, I want to reference other components to that base file. I'm wondering if this approach is correct, and how I ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

A beginner's guide to retrieving random names and images from JSON data for every object using JavaScript

I have a creative idea for a random ruffling game, where it picks a user's name and image randomly. However, I'm facing an issue with ensuring that each image matches the correct user when selected randomly. I want to make sure that every objec ...

Flexbox allows you to easily manage the layout of your website

I am currently working on a CSS project and have encountered an issue. Whenever I apply the "display: flex" property to the .student element, the border around it mysteriously doubles. The reason for wanting to use the flex property is to align the text ve ...

GitHub Action CI/CD for a Next.js app's directory path

I'm currently facing an issue while deploying from the app directory to Github Action CI/CD. I keep running into a PageNotFoundError: Cannot find module for page: / error, indicating that I may not be able to access the app path in my structure. Here& ...

What are the precise steps to create a flawless scrolling area?

I am facing an issue with setting accurate scroll zones for my divs. Here's my ideal scroll zone location: scroll zone in red Currently, I have a maximum of 4 divs and each div should contain a total of 10 rectangles per category (concentration, boos ...

Creating a scrollable HTML5 div container with fixed divs positioned within it

I am attempting to develop an app container that mimics the functionality of Microsoft Excel. The container should scroll both horizontally and vertically, with fixed headers on the left and top that move along with the content. Here is a rough representat ...

Height of cells is often overlooked in webkit browsers

When adjusting tbody and thead heights, I noticed that webkit does not behave like other browsers. I've set the height of td. Here is an example of what I am referring to: link The question at hand is - which browser is displaying correctly? And ho ...

The absence of a scroll bar on the web application is preventing me from scrolling properly

The vertical scroll bar on my Angular app seems to have disappeared mysteriously. I haven't made any changes to the code recently, and I'm struggling to figure out why it's missing. I've spent days trying to troubleshoot this issue with ...

Printing a React component using a button causes formatting related to className to be lost, while printing it inline preserves the formatting

I've hit a roadblock in trying to figure out the React and printing issue for the past week and a half, and it feels like I'm going in circles. Despite finding some helpful solutions on Stack Overflow, none of them seem to work completely for me ...

Gap in footer spacing on Internet Explorer is significantly large

The layout of the page is split into two main sections: A large header that takes up 100% of the browser height The main content area and footer When viewing the page in a browser, only one of these sections will be visible. The following code works wel ...

When disabling JavaScript in the browser, the styled-jsx library fails to render the applied styles (specifically when using Rollup with styled-jsx)

Can anyone lend a hand? I'm currently working on a blog project that requires functionality even when javascript is disabled in the browser. While using the project "https://github.com/dionatanaraujo/rollup-styled-jsx" (a fork of "https://github.com/ ...

Tips for confining a float within a div with fluctuating space

I have a scenario where I have multiple divs ('group') containing text, and there is a floated div ('toggle') in the bottom corner. The current code works well if the text length in 'group' is consistent, but the position of t ...

Struggling to achieve proper alignment for a series of div tags

I have implemented a code block to read in an image pixel by pixel and display it as a series of div tags arranged in a table-like fashion. The code is mostly inspired by a comment on PHP.net (http://www.php.net/manual/en/function.imagecolorat.php). This i ...

Learn how to use Bootstrap to style your buttons with centered alignment and add a margin in between each one

Looking to center four buttons with equal spacing between them? Here's what you can do: |--button--button--button--button--| Struggling with manual margin adjustment causing buttons to overlap? Check out this code snippet: <div id=""> ...