Scrolling div without fixed height

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

I need to build a dynamically-resizing scrolling div.

The div should dynamically resize to fit the screen. But if the content doesn't fit on the screen, it should display a scrollbar. So the browser's own scrollbar should never need to become active.

I can get a scrollbar to appear in the div by placing another div inside it and using overflow: auto.

<div id="gridcontainer" style="overflow:auto;height:300px; width:100px;" >     <div id="gridcontent" style="height:100%">     <!--Put loads of text in here-->     </div> </div> 

The trouble is that this only works when the first div has a fixed height. I had hoped I could just set the first div to height:100%, but sadly not- this property appears to get ignored, and the scrollbar just doesn't appear.

I have tried putting the divs in a table with height:100%, and setting the first div to height:auto, hoping it might take its height from its parent. But the div still seems to ignore the height property.

So my question is: Can this be done using just html, or- failing that- javascript?

回答1:

You could stretch the div using absolute positioning. This way it will always take the size of the browser window (or the closest positioned ancestor).

Given this HTML:

<div id="gridcontainer"></div> 

the CSS should be something like:

#gridcontainer {   position: absolute;   top: 0; bottom: 0; left: 0; right: 0;   overflow: auto; } 

Live Demo



回答2:

If you are trying to make element fit the screen then you can set the value of hight and width of the element to 100%.

You will also need to set the height of html and body

html, body {height: 100%} #gridcontaine {    height: 100%;    width: 100%;  } 


回答3:

Since IE9 you can use viewport units.

Let's say that the height of your container is dynamic, unless it size is grater that the windows height. In that case we stop the expansion & activate the scroll.

#container{   background: #eaeaea;   max-height: 100vh;   overflow-y: scroll; }  .parent div{   outline: 1px solid orange;   width: 200px;   height: 200px;   float:left; }
<div id='container'>   <div></div>   <div></div>   <div></div>   <div></div>   <div></div>   <div></div>   <div></div> </div>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!