I have a Nextjs app that displays the same navbar on each page. The navbar has a fixed
position. The display is correct on the homepage (written in index.tsx
). But when I click on a new page, the new page is hidden behind the navbar!
The issue disappears if I remove the fixed
position property. But I can't believe Nextjs doesn't support such a basic task.
The code is very simple:
// _app.tsx
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Navbar />
<Component {...pageProps} />
</>
);
}
export default MyApp;
// about.tsx
const About: NextPage = () => {
return (
<section>
<h1>About</h1>
</section>
);
};
export default About
// navbar.tsx
export default function Navbar() {
const router = useRouter();
return (
<nav className={styles.navbar}>
<Link href="/">
<Image
src={icon.src}
className={styles.logo}
alt="logo"
width={70}
height={70}
/>
</Link>
<ul className={styles.list}>
<li
className={
router.route === "/about" ? styles.listItemActive : styles.listItem
}
>
<Link href="/about">About</Link>
</li>
</ul>
</nav>
);
}
//navbar.module.css
.navbar {
background-color: var(--dark);
color: #fff;
height: 80px;
width: 100vw;
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
position: fixed;
z-index: 999;
}
.logo {
cursor: pointer;
}
.list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
align-items: center;
}
.listItem {
cursor: pointer;
}
.listItemActive {
cursor: pointer;
color: var(--red);
}
How to fix this?
CodePudding user response:
Just add a position to your css.
top: 0px;
right: 0px;
left: 0px;
https://developer.mozilla.org/docs/Web/CSS/position
CodePudding user response:
If what you want is to have a sticky navbar, you can do it with pure CSS with position: sticky like this:
header, nav, main {
padding: 1.7rem 1rem;
}
header {
background-color: #d99;
}
nav {
position: sticky;
top: 2rem;
background-color: #9d9;
}
main {
height: 100vh;
background-color: #99d;
}
--
<header>
Header
</header>
<nav>
Navbar
</nav>
<main>
Main
</main>