Set a div inside of a div to scroll, while parent

2019-04-17 20:55发布

I have a container div that holds many child divs. One of the divs in my container houses comments. Instead of setting the whole div to scroll, I want everything to stay in place, leaving only the comments div to scroll. I have tried setting the parent overflow to hidden, and the comment div to scroll, and the scrollbar actually shows on the page but it is disabled. Does anyone know how I can accomplish this?

CSS

#container
{                
   position: absolute; 
   overflow: hidden; 
}

#comments
{
   position: relative;
   overflow: scroll; 
}

HTML

<div id="container">
   <div id="comments">
      this is what I want to scroll
   </div>
</div>

I cannot get rid of the container because it houses many more child elements. I just want everything else to stay static while only the comments can scroll.

标签: html scroll
3条回答
Deceive 欺骗
2楼-- · 2019-04-17 21:45

You need to set a specific height on the "comments" div to make sure it knows exactly when to scroll. If there's not enough content to fill up that container beyond the specified height, the scrollbar might appear with overflow:scroll but it will be disabled. If you want the scrollbar to appear only when it's actually needed, you'll want to use overflow:auto as the CSS rule. By setting the height of the child container and not the parent, the parent can grow as necessary.

In your example, the position:absolute on the parent container is not required to obtain the solution; however, you might be including that for some other reason.

查看更多
叛逆
3楼-- · 2019-04-17 21:57

It is disabled because there's no defined height on the element. Overflow auto will populate the scrollbar if you define a height and the content extends past that height.

#comments{
    height:200px;
    width:200px;
    position: relative;
    overflow: auto; 
}
查看更多
戒情不戒烟
4楼-- · 2019-04-17 22:00

You need to add a width and height:

Check out this JSFiddle: http://jsfiddle.net/FgGmQ/

HTML:

<div id="container">
<span>This is the container</span>
<div id="comments">
this is what I want to scroll, this is what I want to scroll,
this is what I want to scroll, this is what I want to scroll,
this is what I want to scroll, this is what I want to scroll, 
</div>
<span>The end of the container</span>

CSS:

#container{
    overflow: hidden;
}
#container span{
    background-color: yellow;   
}
#comments{
    overflow: auto; 
    height: 80px;
    width:150px;
}

Again, just check out this JSFiddle

查看更多
登录 后发表回答