How to fix a Div to top of page with CSS only

Solution 1:

Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following

#term-defs {
    height: 300px;
    overflow: scroll;
}

This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.

#top {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100%;
    height: 23px;
}

This will fix it to the top, on top of other content with a height of 23px.

The final implementation will depend on what effect you really want.

Solution 2:

You can do something like this:

<html>
<head><title>My Glossary</title></head>
<body style="margin:0px;">
        <div id="top" style="position:fixed;background:white;width:100%;">
            <a href="#A">A</a> |
             <a href="#B">B</a> |
            <a href="#Z">Z</a>
        </div>

        <div id="term-defs" style="padding-top:1em;">
           <dl>
               <span id="A"></span>
               <dt>foo</dt>
               <dd>This is the sound made by a fool</dd>
               <!-- and so on ... ->
           </dl>
        </div>
</body>
</html>

It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div. The background and width are there to cover the contents of the term-defs div as they scroll under the top div.

Hope this helps.