如何指定div的高度?

时间:2011-02-11 08:22:55

标签: css

我想为前两个div指定固定高度,为下两个div指定百分比值。

最后一个div应该占用前div所遗漏的所有空间(到浏览器窗口的底部)。我如何在CSS中实现这个目的..?

这是我的css + html。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<title>One Hundred Percent height divs</title>
<style type="text/css" media="screen">
html
{
height:100%;
}

body 
{
margin:0;
padding:0;
height:100%;
}
header
{
height:20px;
width:100%;
background-color:red;
}
.container2
{
height:40px;
width:100%;
background-color:#11ccdd;
}
.container3
{
height:35%;
width:100%;
background-color:#bacdef;
}
.subcontainer1
{
float:left;
height:35%;
width:50%;
background-color:#569895;
}
.subcontainer2
{
float:left;
height:35%;
width:50%;
background-color:#dbc462;
}
.container4
{
width:100%;
background-color:#aaaadd;
}
</style>
</head>

<body>

<header>
header
</header>

<div class="ClearAll"></div> 
<div class="container2">
container2
</div>
<div class="ClearAll"></div>

<div class="container3">
<div class="subcontainer1">
subcontainer1
</div>
 <div class="subcontainer2">
subcontainer2
</div>
</div>

<div class="ClearAll"></div>


<div class="container4">
container4


</div>

</body>
</html>

我需要提到前两个div的宽度像素值,就像我在这里写的那样。 第三个容器具有宽度的百分比值。第四个容器应占据其余三个div所剩余的空间(屏幕大小)。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

你不能用CSS做到这一点。你可以做一些黑客来达到同样的效果,这取决于你想做什么,但你没有真正提到为什么你需要这样做。

对于设计为以任何方式填充屏幕的复杂布局,如果你想看看,有一个非常聪明的jquery插件叫做砌体,可以帮你解决这个问题。

http://desandro.com/resources/jquery-masonry/

答案 1 :(得分:1)

您可以使用此JQuery脚本:

function resizeContainer() {
    var screenHeight = $(window).height();
    var allElements = $('header').height() + $('.container2').height() + $('.container3').height();
    var container4Height = screenHeight - allElements;
    $('.container4').css({
        'height': container4Height
    });
}

resizeContainer();

$(window).resize(resizeContainer);

演示:

http://jsfiddle.net/Mutant_Tractor/NSh35/2/

这不能在CSS中完成并且看起来100%完美

相关问题