简体   繁体   中英

How to Set Fixed-Position Element Height to Reach Bottom of Browser Window?

I have a page with a header at the top, a sidebar on the left, and a main content area on the right. A simplified version can be seen at http://jsbin.com/iqibew/3 .

The sidebar has the styling position: fixed so that it does not scroll with the rest of the page. This works but I also need the sidebar itself to scroll if it's content is too long to fit.

This is only possible if I can set the correct height for the sidebar. But I can't find any way to set this height. 100% is close but it's too tall because the sidebar starts below the header.

Is there no way to address this. I'm open to either a CSS or JavaScript/jQuery solution.

I suppose I'll post this, since it seems to work:

div#header-div {
    height: 90px;
    background-color: lime;
    margin: 0;
}
div#fixed-div {
    position: fixed;
    left: 0;
    top: 0;            /* <<< No offset */
    bottom: 0;         /* <<< Pull to the bottom for height */
    margin: 120px 0 0; /* <<< Give it the 120px top */
    width: 260px;
    background-color: silver;
    overflow-y: scroll;
}

http://jsbin.com/iqibew/13/

if you want your div to be sized as you like , i have an option for you

//Add this to <head> section , i thought you haven't one in the sample

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"  >
</script>

      <script type="text/javascript"  >
$(document).ready(function() {

function _resizeTDiv()
{
   var p = $("#header-div");
   var position = p.position();
   var realheight = p.position().top+p.height();
 $("#fixed-div").height( $(document).height()-realheight -5); //+-5 Error? , not needed
}
 _resizeTDiv();

//Resize  our div on window resize?
$(window).resize(function() {
 _resizeTDiv();
});

});

</script>

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