如何保持div的高度100%?

时间:2014-08-13 19:00:48

标签: css

我有2个网格:一个侧栏和一个主要部分。我希望侧边栏的div高度为100%。 然而,主要部分的高度打破了..我不明白为什么/为什么会发生......

要明确:

页:

 <div class="wrap">

 <div class="section group">    

 <div class="col section_1_2">
    <div class="sideBar">sideBar</div>
 </div><!--section_1_2-->

 <div class="col section_2_2"> 
    <div class="layout">layout
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    </div>
 </div><!--section_2_2-->    

 </div><!--section group-->   

 </div><!--wrap-->

的CSS:

 *{margin:0;padding:0;}

 body,html{height:100%;}

 .wrap{
 width:100%;
 height:100%;
 }

 .sideBar{
 width:100%;
 height:100%;
 background:lightblue;
 }

 .layout{
 width:90%;
 height:auto;
 background:blue;
 margin:0 auto;
 }

 .layout span{
 width:200px;
 height:500px;
 background:yellow;
 display:block;
 clear:both;    
 }

 /* fluid grids */
 .section_1_2{
 width:20%;
 height:100%;
 }
 .section_2_2{
 width:80%;
 height:100%;
 }

 /* Grid settings*/
 .section{
 clear:both;
 padding:0;
 margin:0;
 height:100%;
 }
.group:before,
.group:after{
 content:"";
 display:table;
 }
.group:after{
 clear:both;
 }
.col{
 display:block;
 float:left;
 }

所以会发生的情况是:如果我不添加这些span标签(额外的2000px高度),侧边栏将正确显示(100%高度)但是如果我在布局中添加长高度内容则会打破100%的高度侧边栏..

那么这里到底发生了什么?是什么改变了页面或侧边栏的高度?

请点击此处:http://jsfiddle.net/83noLsjv/1/

这可能是非常简单但我看不到保持侧边栏100%高度并同时在布局中添加长内容的解决方案...

提前谢谢!

3 个答案:

答案 0 :(得分:1)

高度的计算方式与宽度不同 - &#34;浏览器根本不评估高度,除非内容太长以至于超出了视图端口&#34;。

这篇文章描述了你在这里遇到的确切问题: http://webdesign.about.com/od/csstutorials/f/set-css-height-100-percent.htm

参考:&#34;当您为父元素设置了高度的元素设置百分比高度时,会出现问题。换句话说,父元素具有默认高度:auto;。实际上,您要求浏览器根据未定义的值计算高度。由于这将等于空值,结果是浏览器什么都不做。&#34;

答案 1 :(得分:1)

尝试将您的位置设置为固定在css中的侧边栏。

位置是:固定

答案 2 :(得分:0)

另一种方法是在您想要滚动的主容器上使用overflow: auto

http://jsfiddle.net/MathiasaurusRex/vx7pzjd6/

相关问题