Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

scroll

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.

like image 315
user981053 Avatar asked Dec 15 '11 20:12

user981053


People also ask

How do I scroll a div inside another div?

To fit all the text inside the div, the single-direction scrolling method will be used. You can apply it by placing the overflow-y:scroll in the id growth inside the style tag. Notice the scroll bar on the right side of the div .

How do I force a div to scroll?

Set the overflow-x:hidden; and overflow-y:auto; that will automatically hide the horizontal scroll bar and present only vertical scrollbar. Here the scroll div will be vertically scrollable.

How do you make a div not move when scrolling?

As for preventing scrolling on the div, all you need to apply on the footer is overflow: hidden; and that should do the trick. Actually margin:0 auto; is not going to help with position:absolute;.


2 Answers

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.

like image 117
TLS Avatar answered Sep 23 '22 03:09

TLS


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;  } 
like image 20
Kai Qing Avatar answered Sep 22 '22 03:09

Kai Qing