[英]Resize div to fit screen
When the text is added on top,the div moves down and the text on bottom is not visible. 当文本添加到顶部时,div向下移动,底部的文本不可见。 I want the divs to resize so that everything fits into container keeping the width and height to 100%. 我希望div调整大小,以便所有东西都适合容器,保持宽度和高度为100%。
Is there are any way to do this with CSS or do I need JavaScript? 有没有办法用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>
Using jquery you can achieve like below. 使用jquery你可以实现如下。 Count total number of tags in container div and divide the 100% height among those element. 计算容器div中的标签总数,并在这些元素中划分100%的高度。 SO all the items will be visible with overflow:hidden
所以所有的项目都可以看到overflow:hidden
Please check below snippet. 请查看下面的代码段。
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>
You could use CSS flex for this. 你可以使用CSS flex。
It could look something like this: 它可能看起来像这样:
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>
Change the height of .img
to 40%. 将.img
的高度更改为40%。 Because taking 50% height is making it consume the entire height. 因为占据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>
Css Code Css代码
body,html,p {
margin: 0;
padding: 0;
}
Script 脚本
$(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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.