Using CSS to Create a Fixed Header

Fixed headers are a popular trend in web design, and adding one to your site can be as easy as adding a position: fixed line to your CSS, but often it’s a little more complicated than that. Some other styling factors you’ll need to consider are top, width, and z-index. It’s important that you set top to 0 if you want the header to be fixed to the very top of the page. Additionally, you’ll probably want to make the width of the header 100% if it isn’t already — the fixed header might look a little strange as you scroll down the page if it doesn’t take up with entire width of the screen. You should also definitely add a high z-index to ensure that the header scrolls over all of the content below it, not underneath it.

Here’s an example of what the typical CSS code might look like to make a header appear to be fixed.

Join us in our newest publication:
  1. .fixed-header{
  3. position: fixed;
  5. top: 0;
  7. width: 100%;
  9. z-index: 10000;
  11. }

If you’d like the header to be positioned statically or absolutely and then be fixed once you’ve scrolled past it, you can do this using simple jQuery and JavaScript to calculate the height of the area above the header, and have the fixed styling added dynamically to the header after the user has scrolled past that point. In the following example, #nav is the header, #top is the area above the header, and .fixed-header is the CSS class that contains the fixed positioning styling:


  1. var n = $("nav");
  2. var height = $('#top').height();
  4. $(window).scroll(function(){
  5. if($(this).scrollTop()>height){
  6. n.addClass("fixed-header");
  7. }
  8. else{
  9. n.removeClass("fixed-header");
  10. }
  11. })

Share and Enjoy !

0 0