简体   繁体   中英

Creating a relatively positioned scrolling div

I am trying to create an effect where I have a small header on a page which always remains visible at the top, followed by the rest of the page which can scroll up and down.

At the moment the header scrolls off the page as soon as the page is scrolled, which is not what I want. I thought about making the second part of the page a scrolling div, similar to this answer , but unfortunately that approach seems to require that I know ahead of time the height of my header div and I do not - the reason being that it is possible the height will change based on the width of the page, so if the page is not wide enough part of the header will spill onto the next line. For this reason absolute position also seems out of the question, as I can't know ahead of time where the position of the second div will be - it should just come right after the first div, no matter where it is, ie relative position but it seems absolute positioning is part of the trick to make a scrollable div work.

So how can I achieve a scrolling DIV that is positioned relative to another element on the page using only CSS?

Position the header element with:

position: fixed;

That will make it "fixed" relative to the browser window, regardless of how much you've scrolled.

Ok, taking @zigdawgydawg's answer as inspiration I found that this code will work.

<!doctype html><html style="height:98%;">
<body style="height:100%;">
<div> ... contents of first div ... </div>
<div style="position:fixed; overflow:auto; height: 100%;">
... 
contents of second div 
...
</div>
</body></html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM