简体   繁体   中英

Make a div fill the remaining dynamic height and scroll without javascript

I have a document structure that maintains the header at the top of the page and the footer at the bottom. It's working well as long as the content in the middle is less than the height of the window. If the content is too long, the footer gets pushed further down the page and a full body scrollbar is displayed. How can I get the scrollbar to be limited to the content DIV.

Note that the content of the header and footer are not fixed so I don't know the height of those elements and can't set the top position of the content element as a fixed value. I've added a show/hide feature in the example to demonstrate this.

I'm trying to resolve this in pure CSS (avoiding Javascript). I know that using javascript, I could monitor changes to window size and element visibility, I could calculate the height of the header and footer and set fixed dimensions to the content element. But is there a non-javascript solution?

http://jsfiddle.net/sA5fD/1/

html { height: 100%; }
body {      
    padding:0 0;
    margin:0 0;
    height: 100%;
}
#main {
    display:table;
    height:100%;
    width:100%;
}
#header, #footer {
    display:table-row;
    background:#88f;
}
#more {
    display: none;
}
#content {
    display:table-row;
    height:100%;
    background:#8f8;
}

It should work for all modern browsers, desktop, tablets and mobiles. For old browsers, a full body scrollbar would be ok.

If you add two wrap blocks:

<div id="content">
  <div id="content-scroll-wrap">
    <div id="content-scroll">
      content...

Then use CSS:

#content-scroll-wrap {
    position: relative;
    height: 100%;
}
#content-scroll {
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    overflow: auto;
}

http://jsfiddle.net/sA5fD/8/

Don't know about support in old browsers. IEs might need some fixes.

For future visitors:

HTML

<div class="parent"> 

  <div class="child">
    <div class="large-element> </div>
  </div>

</div>

CSS

 .parent {
   height: 1000px
   overflow-y: scroll; 
 }

 .child {
   background-color: royalblue;
   height: auto;
 }

 .large-element {
   height: 1200px; 
 }

In this scenario, the child element will create an overflow. Since the child's height is set to auto, it will stretch out to fill the container. If you had set it to 100% , it would only go 1000px , leaving some white space beneath!

Here is a pen: https://codepen.io/meteora/pen/JJYoZM

This should work in all browsers :)

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