Using CSS to Create a Fixed Header

Datetime:2016-08-22 23:02:12          Topic: CSS           Share

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.


position: fixed;

top: 0;

width: 100%;

z-index: 10000;


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:

var n = $("nav");
var height = $('#top').height();


About List