samedi 5 mai 2012

CSS Sticky Header and Footer with Scrolling Middle

This is a way to use CSS only (no JavaScript) to have the content expand to fill the window size, with the header always visible at the top and the footer always visible at the bottom.  If there's too much content, just the middle will scroll, not the whole page. You can see it in action, here.

It's not perfect, but I think it's the best you can get without JavaScript and it does work perfectly on most mobile phones, which is the reason I did it.

Before I get onto the code, I'd like to thank Ryan Fait for pointing me in the right direction, with his Sticky Footer.

The basic code is below.  I've used in-line styles to make it easier for you to see which styles are applied to which bit, but obviously you should put them into a separate stylesheet and also add fonts and change background colours etc.
<html style="height:100%;margin:0;">
<head>
<title>Scroll Demo</title>
</head>
<body style="height:100%; margin:0; padding:0;">
            <div style="height: 4em; background-color:#000000; color:#ffffff; position:relative; z-index:1;">Header Strip</div>
           <div style="height: 100%; margin: -4em 0 -2em 0; color:#000000; overflow:auto;">
              <div style="height:4em;"></div>
              <p>THIS IS WHERE THE CONTENT GOES</p>
       <div style="height:2em;"></div>
           </div>
           <div style="height: 2em; background-color:#000000; color:#ffffff; position:relative; z-index:1;">This is the footer</div>
    </body>
</html>
The important points are that you need to apply a 100% height style to the <HTML> and <BODY> tags as well as your main content div. The header and footer need to have a z-index of 1, otherwise your content will scroll over them. Your main content div needs to have an empty div that is the same height as your header at the top, and an empty div that is the same height as your footer at the bottom. Finally, you need to apply negative margins that are the same as the header and footer heights, to the top and bottom on your main content div.

There is a demo here, with the exact code written above, except for additional content to force the scroll.

The reason I wrote this was because I needed to find a way to make my HTML5apps fill the full screen, without going off of it, on all the various resolutions. I've tested my apps on iOS, Android and Symbian so far and the scrolling middle works.

Aucun commentaire:

Enregistrer un commentaire