Fixed Headers

Asif Ahmed

It’s been a while since I’ve posted, but I have learned a great deal over these past 6 weeks. I just haven’t gotten around to posting about it. Last time I posted I had been learning about jQuery and Postgres, but now my learning has progressed into project based learning in PHP, and mySQL. Last time I was taking a Software is a Service from BerkeleyX, and now I’m taking Cryptography from Stanford. I would say that the Stanford class is much better taught as it is meant for a web audience rather than a classroom audience.

Most my posts from now on will be shorter, but showcase one topic. Today we will be focusing on fixed headers on a web page.

A lot of pages we go to now have a header up top that stays with you as you scroll down the page. This header will often consist of a logo, or an image, and some navigation links. How would we accomplish this fixed header functionality? This can be done rather easily with CSS.

	div.header{
		background-color: yellow;
		width:100%;
		height:150px;
		position:fixed;
		top:0;
		z-index: 1;
		opacity:0.8;
	}

Here I have written the CSS for a div with the class “header”. The first three lines just choose the color, width, and height. The next three lines are the ones that are important for making the header fixed. position:fixed will ensure that the header will remain fixed no matter where you scroll along the web page. top:0; will make sure that this div is 0 pixels away from the top. If we used bottom instead of top, this would be a fixed footer. z-index: 1;means that this div will be “on top” of everything else. If we set this to 0, we would see the body text scroll on top of the header as we scroll down the page. If this is greater than the z-index of the body then the body text will go behind the header. We can see the body text go behind the header as we scroll because the opacity of this div is less than 1.

However if we leave this just as it is, any text in the following divs would become hidden behind this header. That is why we must make sure to have this CSS on the following divs – padding-top:150px;. 150px was the height of our header so this will ensure that the content in the next div will start at least 150px from the top.

To see this fixed header in practice, please visit here.