2016-10-03 139 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); 
});