Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 如何设置div的高度与其容器匹配_Html_Css - Fatal编程技术网

Html 如何设置div的高度与其容器匹配

Html 如何设置div的高度与其容器匹配,html,css,Html,Css,我有一个箱子。此div包含2个div标记,如下所示: <style type="text/css"> #container{ height:100% } #child1{ height:35px; } #child2{ overlow-y:auto; height: ??? /**to match remain space of container**/ } </style> <div id="container">

我有一个箱子。此div包含2个div标记,如下所示:

<style type="text/css">
#container{
    height:100%
}

#child1{
    height:35px;
}

#child2{
    overlow-y:auto;
    height: ??? /**to match remain space of container**/
}
</style>


<div id="container">
    <div id="child1">this is a child1</div>
    <div id="child2">this is a child2</div>
</div>

#容器{
身高:100%
}
#孩子1{
高度:35px;
}
#孩子2{
超长y:自动;
高度:???/**以匹配容器的剩余空间**/
}
这是一个孩子
这是一个孩子

如果child2的内容太多,如何设置child2的高度以匹配容器的剩余空间(垂直滚动条)?

一个选项是使用相对和绝对定位的组合:

#container{
    height:100%;
    position: relative;
}

#child1{
    height:35px;
}

#child2{
    overflow-y:auto;
    position: absolute;
    width: 100%;
    top: 35px;
    bottom: 0;
}
实际上,您根本没有设置高度,而是从顶部创建元素
35px
,从底部创建元素
0px


我不明白你的问题,我想你想让它滚动?如果是的话

child2{
overlow-y:scroll;
height: 100%;
}

我希望这有帮助

另一种解决方案是使用
calc

#child2{
    overlow-y:auto;
    height: calc(100% - 35px);
}


IE9+

您可以尝试使用计算功能

      height: calc(100%-35px)
      height: -webkit-calc(100%-35px)
      height: -moz-calc(100%-35px)

我从来没有真正使用过这个,可能不是所有的浏览器都支持这个,但我认为它可以工作。

有一个错误,或者我认为这是css中的一个输入错误
overlow-y

创建一个函数来调整
child2
的高度,该函数将在页面加载时调用,并在更改
容器高度的事件中调用

注意:-滚动小提琴输出容器下方有一个按钮,用于更改容器的高度

$(document).ready(function(){
    setHeight();

     $('#change').click(function () {
        $('#container').css('height', '300px');
        setHeight();
     });

});

function setHeight (){
    $('#child2').css('height', $('#container').height() - 35 + 'px');
    $('#child2').css('max-height', $(this).height())
}

将容器的最大高度固定为其当前高度,子2的高度应等于容器高度-35px谢谢您的回复。我无法确定容器的高度,因为它是动态值。谢谢James,若child2的内容太长,滚动条将不会出现@user532017有效,您刚刚在
溢出中输入了一个错误。谢谢你的解决方案。我有一个新问题。如果child1的高度是自动的,那么如何将child1的高度设置为滚动条?calc只在ie9+上工作,但我想在ie7,8上测试。谢谢谢谢你,詹姆斯!你是IE7和IE8的解决方案吗?谢谢。如果您将高度设置为100%,则child2的内容将丢失在底部。谢谢UDB。这是一个很好的解决方案。如果浏览器已调整大小,则高度已更改?@user532017将在重新调整浏览器窗口大小的情况下工作,您必须在“窗口调整事件”中调用
setHeight
。请注意,演示程序在JSFIDLE中无法正常工作,因此请复制并创建html文件,以查看它是否能正常工作,以供参考。