CSS,直到垂直拉伸div达到其父元素高度

9

我被包含在一个名为 pageWrapper 的容器中,该容器内有三个纵向排列的div。第一个(头部)和最后一个(navWrapper)有固定高度。我需要中间的那个(contentWrapper)在高度上能够自适应,直到父级div pageWrapper 达到最大高度(根据浏览器视口大小而定)。

我画了一个 示意图 来说明这个问题。 enter image description here

这是我当前解决方案的示例代码。 http://jsfiddle.net/xp6tG/

以下是CSS和HTML代码:

html, body{
  height: 100%;
}

body{
  background-color: #E3E3E3;
}

#pageWrapper{
  margin: 0 auto;
  position: relative;
  width: 600px;
  height: 100%;
}

header{ 
  display:block;
  width: 100%;
  height: 100px;
  background: yellow;
}

#contentWrapper{
  width: 100%;
  height: 100%;
  background: blue;
}

#navWrapper{
  width: 100%;
  height: 100px;
  background: green;
}
<div id="pageWrapper">
  <header>
    Header
  </header>
  <div id="contentWrapper">
    Content
  </div>
  <div id="navWrapper">
    Nav
  </div>
</div>

它几乎可以工作,但会导致高度过高,从而出现垂直滚动条。

2个回答

11

这是一种方法。

应用以下CSS

html, body{ height: 100%; margin: 0;}
body{ background-color: #e3e3e3;}

#pagewrapper{
    margin: 0 auto;
    position: relative;
    width: 600px;
    height: 100%;
}
header{ 
    display:block;
    width: 100%;
    height: 100px;
    background: yellow;
}
#contentwrapper{
    width: 100%;
    position: absolute;
    top: 100px;
    bottom: 100px;
    left: 0;
    background: blue;
}
#navwrapper{
    width: 100%;
    position: absolute;
    height: 100px;
    bottom: 0px;
    left: 0;
    background: green;
}
由于您为header#navwrapper块元素指定了高度,因此您可以使用相对于父级#pagewrapper块的绝对定位来设置#contentwrapper的底部和顶部偏移以及#navwrapper的底部偏移。
如果您看到滚动条,则可能需要针对html和/或body标签设置margin: 0
演示文稿: http://jsfiddle.net/audetwebdesign/yUs6r/

2
你可以尝试在调用CSS后,将此脚本添加到你的“”部分中。它会查找页眉/页脚元素的高度,并使中心div的高度填充屏幕。这是很好的,因为如果你决定使头部/页脚元素的高度动态变化,此脚本仍将起作用。
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
        var totalHeight = $('#pageWrapper').height();
        totalHeight -= $('header').height();
        totalHeight -= $('#navWrapper').height();

        // Remove an extra 20px for good measure
        totalHeight -= 10;

        $('#contentWrapper').css('height', 'auto');
        $('#contentWrapper').css('min-height', totalHeight);
});
</script>

我还将高度元素设置为最小高度,因此如果您的内容大于设置的高度,则div将像正常情况下扩展。 - Josh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接