Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow hidden with nested overflow scroll not working

Tags:

html

css

I have a problem with a div not being clipped to the parent even though it has overflow: hidden.

I've looked through the overflow: hidden questions here on stackoverflow but most of them either have problems with position or seem to suggest that my code should work.

Here's a MWE, you can find the jsfiddle here:

<div id="parent">
  <div id="scroller">
    <div id="child">
      meh
    </div>
  </div>
</div>

CSS:

#parent {
  height: 500px;
  overflow: hidden;
}

#scroller {
  overflow: scroll;
}

#child {
  height: 10000px;
}

What I expect

#parent has overflow: hidden so #scroller gets clipped to the height of parent. Because its #child is taller than the resulting height overflow: scroll results in a scrollbar.

What happens

#scroller just uses the height of #child and ignores both overflow properties.

What about simple workarounds?

  • In my real world problem there is multiple <div>s in #parent so I can't give #scroller a height.
  • The html is generated automatically so I can't just remove #scroller.

Thanks for all help, Stefan

ANSWER

There actually is a CSS-only answer in the comments with display: flex. See:

https://jsfiddle.net/huocukw7/6/

#parent {
  height: 500px;
  overflow: hidden;
  display: flex;
  flex-direction:column;
}

#scroller {
  overflow: auto;
  flex-grow:1;
}

#child {
  height: 10000px;
}
like image 878
user2296153 Avatar asked Apr 21 '17 09:04

user2296153


2 Answers

All you need to do is provide height to your #scroller

#scroller {
  overflow: scroll;
  padding: 10px;
  background-color: red;
  height: 100%;
}

Demo


As per your point - In my real world problem there is multiple s in #parent so I can't give #scroller a height.

There is no other way you can make it scrollable without assigning a height to it. Without that, it will stretch until the child element ends which won't make your wrapper scrollable.

You can use JavaSript here, to calculate the height on runtime and append it to the element.

like image 143
Mr. Alien Avatar answered Nov 12 '22 20:11

Mr. Alien


There actually is a CSS-only answer in the comments with display: flex. See:

https://jsfiddle.net/huocukw7/6/

#parent {
  height: 500px;
  overflow: hidden;
  display: flex;
  flex-direction:column;
}

#scroller {
  overflow: auto;
  flex-grow:1;
}

#child {
  height: 10000px;
}
like image 42
user2296153 Avatar answered Nov 12 '22 21:11

user2296153