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 CSS Layout Basics Positioning Page Content Fixed Positioning

How to do so that fixed navigation bar doesn't cover content by clicking a button that drops to another part of the web.

I have the following question: I created a fixed navigation bar on my website and I have a button on the banner that goes to another part of the page. When I click the button part of the content is covered by the navigation bar, how can I fix it so that it is just above the H2 in this case?

1 Answer

Joel Bardsley
Joel Bardsley
31,249 Points

Hi Patricia, I've done a quick CodePen that you can use for reference, but here's the main technique I've used:

section {
  position: relative;
}

section::before {
  display: block;
  content: '';
  height: 40px; /* Adjust to match the height of your fixed navigation */
  margin-top: -40px; /* Apply same adjustment as above, so 80px above is -80px here */
}

If you've not yet encountered pseudo elements in css (ie ::before and ::after), then don't worry too much about it yet, Treehouse does cover them in their CSS courses.

Instead of H2 tags I'm using the navigation to link to sections with the particular ids, but this will work for your H2s as well.

The ::before pseudo-class inserts an empty block at the top of your element, so instead of the link taking you to the top of your H2 element, it would take you to the top of the empty space you've just created. I've set the 'content' to an empty string, but bear in mind you could use this to insert some text, symbol or icon instead. The height needs to be at least matching the height of your fixed navigation bar otherwise it won't prevent the overlap. The negative margin-top is optional, but is nice to include as it removes excess space between your elements.

There are JavaScript methods you can use to calculate an offset instead, but hopefully this should help to give you a good starting point.