2012-10-07 128 views
1

我有以下几点:DIV填充剩下的高度计算

<div id="modal-container"> 
    <div id="modal-body"></div> 
    <div id="modal-footer"></div> 
</div> 

我写了一块JS的调整#模体,填补可用空间的其余部分。这实际上是更多的工作似乎比:

$('#modal-body').css({ 
    'height': function() { 
    // the amount of vertical space we have to work with. 
    // this is the height of the container (modalView) 
    var containerHeight = $('#modal-container').height(); 

    // the amount of vertical space the footer takes up 
    var footerOuterHeight = $('#modal-footer').outerHeight(); 

    // we have to also account for the vertical padding of our div 
    var paddingTop = $(this).css('padding-top').replace('px', ''); 
    var paddingBottom = $(this).css('padding-bottom').replace('px', ''); 
    var marginTop = $(this).css('margin-top').replace('px', ''); 
    var marginBottom = $(this).css('margin-bottom').replace('px', ''); 
    var borderTop = $(this).css('border-top-width').replace('px', ''); 
    var borderBottom = $(this).css('border-bottom-width').replace('px', ''); 

    return containerHeight-footerOuterHeight-paddingTop-paddingBottom-marginTop-marginBottom-borderTop-borderBottom; 
    } 
}); 

问题的事实,我们不能为我们的#模体的“outerHeight”属性,因此我们必须考虑到,计算它的茎它自己的填充,边框,边距等。

无论如何,上面的功能大多是有效的。我的2个问题是:

  1. 有没有更好/更简单的方法来做到这一点?
  2. 它似乎是1px关闭。 #modal-container有一个滚动条,因为这一点,如果我减去一个额外的1px,它的工作原理。我错过了什么?除了边距,填充和边界之外,还有其他事项我必须考虑吗?
+0

另请参阅我更新的纯CSS方法的答案。 – Chris

回答

6

有没有更好/更简单的方法来做到这一点?

是的,有。

问题的事实,我们不能设置一个“outerHeight” 属性我们#模体,所以我们必须通过考虑 考虑它自己的填充,边框,边距等

来计算它的茎

这不一定,最终是正确的。您可以使用box-sizing: border-box;,这将强制大小包括边框和填充,但不包括边距。所以你仍然需要处理利润率,但这会为你节省一些工作;

#yourElement { 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
    box-sizing: border-box; 
} 

编辑:为此,您可以使用纯CSS;不需要JavaScript。见this demo。这里的基本轮廓,HTML:

<div class = "container"> 
    <div class = "fluid">Glee is very very awesome! I have margins, too!</div> 
    <div class = "fixed">Glee is awesome!</div> 
</div> 

CSS:

.container { 
    height: 300px; /*whatever you want*/ 
    position: relative; /*necessary*/ 
} 
.fluid { 
    margin: 10px; /*just an example*/ 
    position: absolute; 
    top: 0; 
    bottom: 75px; /*equal to height of bottom fixed-height div*/ 
    right: 0; 
    left: 0; 
} 
.fixed { 
    position: absolute; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    height: 75px; /*whatever you want*/ 
} 

希望这有助于!

+0

感谢您的帮助。我试图使用你的解决方案,但我认为容器“位置:相对”属性给我的麻烦。我需要容器的高度和宽度为屏幕的95%,并且它需要在屏幕上居中。 –

+0

@AndyHin似乎在这里工作得很好:[小链接](http://jsfiddle.net/glee/7gsVM/)。 – Chris

+0

我谈过的很少有人知道这个CSS技巧。魔法是同时设置顶部和底部属性。 – alt