Fixed headers / sidebars

To set an element to be fixed, and not scroll, add the following CSS:

position: fixed;

…but please note that this will cause some strange things to happen at first:

  • Your element will collapse horizontally, so you have to write in a width attribute.
  • The content below your fixed element will be covered by the fixed element, so you’ll need to scoot that element down with margin or padding.

So, if I wanted a fixed header, and this was my HTML:

<header><h1>This is the header</h1></header>
<main><p>This is the main content area.</p></main>

…then here’s the CSS I’d write:

header {
position: fixed;
width: 960px;
height: 120px; /*otherwise it's invisible or really small */
padding-top: 50px; /* to push the text down to be vertically centered in the header */
}
main {
padding-top: 140px; /*to push the main content down below the fixed header */
}

To do this with a sidebar, use the <aside> tag, and adjust your content so the padding is on the left, rather than the top:

<aside><h1>This is the header</h1></aside>
<main><p>This is the main content area.</p></main>

Then, the CSS:

aside {
position: fixed;
width: 120px;
height: 960px; /*otherwise it's invisible or really small */
margin: 0 auto; /* to center text */
}
main {
padding-left: 140px; /*to push the main content right, our of the way of the fixed sidebar */
}
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Both comments and trackbacks are currently closed.