2016-10-03 135 views
3

将文本添加到顶部时,div向下移动,底部文本不可见。我想要div的大小,以便一切适合容器保持宽度和高度100%。将div调整为适合屏幕

是否有任何方式使用CSS来做到这一点,或者我需要JavaScript吗?

body,html { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
#container { 
 
    position: absolute; 
 
    width:100%; 
 
    height: 100%; 
 
    overflow: hidden; 
 
} 
 
     
 
.img { 
 
    background: blue; 
 
    width: 100%; 
 
    height: 50%; 
 
    display: inline-block; 
 
    vertical-align: top;  
 
}
<div id="container"> 
 
    <p>Text 1</p> 
 
    <div class="img"></div> 
 
    <div class="img"></div> 
 
    <p>Text 2</p> 
 
</div>

+2

设置溢出:auto;在.container类中而不是隐藏的 –

+0

即使添加新元素,容器高度也不应增加? –

+0

只会有两个.img元素吗? –

回答

0

你可以使用CSS的Flex这一点。

它可能是这个样子:

body,html{ 
 
      margin: 0; 
 
      padding: 0; 
 
     } 
 
     #container{ 
 
      position: absolute; 
 
      width:100%; 
 
      height: 100%; 
 
      display:flex; 
 
      flex-direction: column; 
 
     } 
 
     .img{ 
 
      background: blue; 
 
      width: 100%; 
 
      height: 50%; 
 
      vertical-align: top;  
 
     }
<div id = 'container'> 
 
    <p>Text 1</p> 
 
    <div class="img"></div> 
 
    <div class="img"></div> 
 
    <p>Text 2</p> 
 
</div>

Fiddle

0

变化.img至40%的高度。因为占50%的高度使其消耗整个高度。

 body,html{ 
 
      margin: 0; 
 
      padding: 0; 
 
     } 
 
     #container{ 
 
      position: absolute; 
 
      width:100%; 
 
      height: 100%; 
 
      overflow: hidden; 
 
      background: #ccc; 
 
     } 
 
     .img{ 
 
      background: blue; 
 
      width: 100%; 
 
      height: 40%; 
 
      display: inline-block; 
 
      vertical-align: top;  
 
     }
<div id = 'container'> 
 
    <p class="text1">Text 1</p> 
 
    <div class="img"></div> 
 
    <div class="img"></div> 
 
    <p class="text2">Text 2</p> 
 
</div>

+0

这增加了滚动条。容器应该适合屏幕 – FBR

+0

然后你将不得不减小.img divs的高度。否则它不适合。 –

1

使用jQuery就可以实现像下面。计数容器div中的标签总数,并将这些元素中的100%高度分开。因此所有的物品都可以用overflow:hidden

请检查下面的代码片段。

var itemLength = $('#container *').length; 
 
$('#container *').css("height",(100/itemLength)+"%");
body,html{ 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
#container{ 
 
    position: absolute; 
 
    width:100%; 
 
    height: 100%; 
 
    overflow: hidden; 
 
} 
 
.img{ 
 
    background: blue; 
 
    width: 100%; 
 
    //height: 50%; 
 
    display: inline-block; 
 
    vertical-align: top;  
 
} 
 
p,img,div{ 
 
    padding:0; 
 
    margin:0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id = 'container'> 
 
    <p>Text 1</p> 
 
    <div class="img"></div> 
 
    <div class="img"></div> 
 
    <p>Text 2</p> 
 
</div>

+1

谢谢,这工作也很好。 – FBR

0

CSS代码

body,html,p { 
    margin: 0; 
    padding: 0; 
} 

脚本

$(function(){ 
var containerHeight= $('#container').height(); 
var pfirstHeight=$('#container p').eq(0).height(); 
var pbottomHeight=$('#container p').eq(1).height(); 
var imgHeight=(containerHeight-pfirstHeight-pbottomHeight)/2; 
$('.img').height(imgHeight); 
});