【Tailwind CSS】fixedプロパティの使いどころ

アプリのメイン画面を作る時、まずサイドバーの部分とメインコンテンツの部分に分けたいですよね(こんな感じに↓)


ただ以下のような実装だとサイドバーとメインコンテンツが横に表示されず、解消方法が分からなかったのでメモとして残しておきます。

サイドバー

export const SideBar = () => {
  return (
    <div className="bg-blue-500 h-full w-[256px]">
      SideBar
    </div>
  )
}

メインコンテンツ

const LearnPage = () => {
  return (
    <div>
      Learn Page
    </div>
  )
}

export default LearnPage

メインページのレイアウト

import { SideBar } from "@/components/sidebar"

type Props = {
  children: React.ReactNode
}

const MainLayout = ({
  children,
}: Props) => {
  return (
    <>
      <SideBar/>
      <main className="pl-[256px] h-full">
        <div className="bg-red-500 h-full">
          {children}
        </div>
      </main>
    </>
  )
}

export default MainLayout


皆さん、どこを直せばよいか分かりますか?

正解は「sidebar.tsxのclassNameにfixedを追記する」です。

修正語のsidebar.tsx

export const SideBar = () => {
  return (
    <div className="bg-blue-500 h-full w-[256px] fixed">
      SideBar
    </div>
  )
}

以下の動画(1:14:28付近)で解説しています。

以上です。