简体   繁体   中英

setting element min-height equal to visible part of the document

i have a page which at least contains a header and a container div i want to set min-height for container div to cover the visible part of document (i dont want to fix it to 100% )

so i thought i can get the document height with the element height and top padding and top margin

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

$(document).ready(function(e) {

    var h = getDocHeight();
    var hedaer = $('.header').height();
    var c = $('.container').css('height') ;
    var m = $('.container').css('padding-top') ;
    var p = $('.container').css('margin-top') ;
    var n = parseInt(h) -  parseInt(c) -   parseInt(m) - parseInt(p) - parseInt(hedaer) ;
    var n = n +  parseInt(c)   ;
    $('.content').css('min-height' , n+'px');

});

but i always end up with more or less there are many other elements inside my container with their own height and padding and margins and it just gives me headache to think about them

is there any simpler way to do this ?

Not exactly sure of what you want, and my answer may not be fitting depending on what browser you're targetting, but display: box might be the solution (code for webkit, to adapt for other vendor prefixes):

<div class="container">
  <div class="header">blue</div>
  <div class="content">red</div>
</div>

and css

.container {
  /*create a vertical box*/
  display: -webkit-box;
  -webkit-box-orient: vertical;
  /*ensure it takes of all available width and height in my fiddle :-D */
  position: fixed;
  top:0; bottom: 0; left: 0; right: 0;
}
/*so that we see something*/
.header, .content {background: blue;margin: 20px;padding: 40px;}
.content {
  margin: 20px;
  padding: 40px;
  background: red;
  /*this div will have all available height in his parent, 
    minus what's already taken, with the beauty of box-flex */
  -webkit-box-flex: 1;
}

... still a very unstable and unsupported spec, but I thought that could be worth mentionning. you can see it in action (with chrome or safari) here http://jsfiddle.net/S6F3S/1/

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