Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

John Rothra
John Rothra
6,711 Points

Need help making the navbar fixed while still using flexbox

I'm trying to work it out on CodePen first and I'm struggling. I know flexbox and position: fixed; don't get along. However, I really need -- okay, want -- this to work.

Codepen: https://codepen.io/jrothra/pen/jmMbWX

I've heard JS can be used, but I don't know JS. However, CSS would be better, I think.

In the end I want the navbar to be transparent when at the top, then become dark gray as people scroll down. The color change will come later; the sticky nav comes first. The reason for the transparency is there will be a full-page hero image on the main index and a full width image on pages/posts.

Help, please!

4 Answers

Hi John

Have you tried to make your navbar fixed?

#navbar {
position: fixed;
width: 100%;
}
John Rothra
John Rothra
6,711 Points

I have. It negates the flexbox, or at least the justify-content:space-between declaration. Both the logo & hamburger end up on the far left (or in this case, "LOGO" and "NAV" respectively). Also, the box ends up no longer full width.

I tried adding width:100% [or 100vw] and it bled off the viewscreen on the right.

You're free to add those declarations in the codepen and you'll see what I mean.

add box-sizing to the navbar, this should solve the bleeding off the viewscreen.

box-sizing: border-box;
John Rothra
John Rothra
6,711 Points

That fixed it! Again, many thanks.

On CodePen there is a white bar at the top, but on my site that I'm working on, there is no white bar.

https://codepen.io/jrothra/pen/jmMbWX/

Hi John

That's the h1 causing the white bar at the top, just add:

h1 {
margin-top: 0;
}
John Rothra
John Rothra
6,711 Points

Chris,

Glad you found it. Since it worked fine on my site I didn't spend much time looking into it on CodePen. However, I'll make the change there for others who may want to use the code.

Hi John

Glad to hear. Good luck with your site!