0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

position: fixed指定したら横幅短くなったし、要素が隠れてしまった時の対処法

Posted at

前提

  • M2 Mac 12.5.1
  • Node.js 16.17.1
  • Next.js 12.3.1
  • tailwind 3.1.8
  • GoogleChrome 105.0.5195.125

SPAとかSSRとか関係なく、HTML/CSSの話なので環境が違っても役立つ話かと思います
ただし、tailwindを使用しているので、CSSの書き方は読み替えお願いします

理想

image.png

現実

fixedを指定したあとは...

image.png

やったこと

  • ヘッダ部分にposition: fixed;を追加
// navbar.tsx
import Link from 'next/link'

export const Navbar = (): JSX.Element => {
  return (
-    <header className="text-center bg-c1 text-c5 py-4">
+    <header className="fixed text-center bg-c1 text-c5 py-4">
      <div className="flex flex-wrap flex-row text-3xl justify-center">
        <Link href="#section-profile">
          <a className="px-3 hover:underline decoration-c2 hover:decoration-4">Profile</a>
        </Link>
// ...略...
      </div>
    </header>
  )
}

解決策

横幅が短くなってしまう

  • position: fixed;を指定しているところにwidth: 100%;を追加
// navbar.tsx
import Link from 'next/link'

export const Navbar = (): JSX.Element => {
  return (
-    <header className="fixed text-center bg-c1 text-c5 py-4">
+    <header className="fixed w-full text-center bg-c1 text-c5 py-4">
      <div className="flex flex-wrap flex-row text-3xl justify-center">
        <Link href="#section-profile">
          <a className="px-3 hover:underline decoration-c2 hover:decoration-4">Profile</a>
        </Link>
// ...略...
      </div>
    </header>
  )
}

要素がヘッダーの下に隠れてしまう

  • ヘッダーの高さ以上の十分なpaddingをとる
// index.tsx
// ...importは省略...

const Home: NextPageWithLayout = () => {
  return (
-    <div className="container text-center">
+    <div className="container text-center py-52 sm:py-40 md:py-20">
      <Head>
        <title>サンプル</title>
        <meta name="description" content="サンプル" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <h1 id="section-profile" className="text-3xl">
        Profile
      </h1>
      <div className="py-10">なまえ: じゅげむじゅげむ</div>
    </div>
  )
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?