Creating a Fixed Header
Creating a fixed header on a page is pretty straightforward. Basically,
you’re just using CSS to fix the header to the top of the page and then
adding a top margin to the main content area.

Standard Fixed Header

[CodePen height=300 show=result href=bHkfy user=maplethorpej ]


Using jQuery with Anchor Tags for a Scrolling Navigation

The problem with using anchor-tag navigation with a fixed header is that
the header overlaps some of the content. To fix this, we need to make sure
that there is always a margin (the header’s height) between the top of the
page and the top of the content. You could use some hacky CSS to get
around this problem, but that isn’t a very scalable solution. Let’s use
javascript to create something more robust.
The Desired Outcome

[CodePen height=400 show=result href=dikFr user=maplethorpej ]


The Javascript

  1. Once a link is clicked…
  2. Store the “href” attribute in the variable “section,” which will be used to target the div to scroll to.
  3. Store the total height of the fixed header in the variable “head_height.”
  4. Assign the variable “adjustment” a value depending on which link was clicked (adjustment is the number of pixels to add to the margin, which can also be negative).
  5. Add the fixed header height and the adjustment height and store it in the “spacing” variable.
  6. Scroll the page to the top of the section minus the desired spacing.

The important thing to note is the adjustment variable. This defines the
number of pixels the section sits below the header.

The HTML and CSS here are pretty simple, so I won’t bother explaining them.

Note #main div { height:400px; } was only added to make the page tall
enough for the example.


This setup will give you the most flexibility. However, if you want every
section to sit at the same margin below the header, you could simply set
the adjustment variable without using the switch function.

If you have any questions or improvements to the code, please comment.

Blog Categories: Website Design | Industry Trends | Mobile | Online Conversion | Pay-Per-Click | SEO | Social Media