Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Fix a DIV to the top of a page with CSS

Use pure CSS to position a DIV at the top of a web page so that when users scroll down, the DIV will remain visible at the top.

Many websites today utilise a banner or header at the top of their website which appears to ‘float’: That is, when the website is scrolled down, the banner remains at the top of the browser window.

Examples of such use can be seen on Flickr, Facebook, Pinterest and Twitter. Typically, such floating DIV’s are used to display the website logo and a small list of menu items. They can also be used to display alerts or marketing messages.

I like some of the newer HTML5 elements, so I have written the following code to utilise the header element to create the banner at the top of the page. In this instance, our header has a height of 8em and a black background colour.

header {
	margin: 0px;
	height: 8em;
	display: block;
	background-color: black;
	position: fixed;
	z-index: 999;
	width: 100%;
	top: 0em;
	left: 0em;
}

The corresponding HTML would therefore be:

<header>Your header text or images here...</header>

If you would rather not use the header element, a standard div with an assigned class can be used in the same way:

.header {
	margin: 0px;
	height: 8em;
	display: block;
	background-color: black;
	position: fixed;
	z-index: 999;
	width: 100%;
	top: 0em;
	left: 0em;
}

Corresponding HTML:

<div class="header">Your header text or images here...</div>

The Z-index value is what keeps the header or div above the other page elements. You will need to ensure that no other elements have a Z-index value above 999.

   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.