30

I have a div with following style: height:250px;scroll:auto;. I want it to scroll after 250 px but should have height according to the content in it.

For example, if the content in it is 100px, then, the height of div should be 100 without scroll. But, if the height exceeds 250px, it should show scroll.

How can do it?

Salman Virk
  • 12,007
  • 9
  • 36
  • 47
  • 1
    I want small content to have small height so that one line should not have 250px height. But, also want the scroll to appear after 250px. Hope it makes sense !!! – Salman Virk Feb 17 '11 at 22:28
  • Anyone who sees this question now should go to [this answer](http://stackoverflow.com/a/42034296/6901876), as it is a great answer that is cross-browser and works in ALL major-browsers. – Cannicide Feb 03 '17 at 23:02

5 Answers5

46

Is this what you are after?

Demo

CSS:

.dyn-height {
    width:100px;
    max-height:250px;
    overflow-y:scroll;
}

height: optional - just for the demo.

Myles Gray
  • 8,711
  • 7
  • 48
  • 70
  • For those using Bootstrap 5 and trying to make a scrollable ````````: this class does not work on it. You have to add the class to a surrounding div element like this ````
    ....````.
    – MikhailRatner Mar 14 '23 at 20:13
20

try this: max-height should do the trick.

html

<div class="height">
    blah<br/>
    blah<br/>
</div>

css:

.height { max-height:250px; border:1px solid red; overflow:auto; }
Mauro
  • 589
  • 5
  • 15
  • When this is not working, adjusting `line-height` helps. http://stackoverflow.com/questions/10251369/css-max-height-and-overflow-auto-always-displays-vertical-scroll – Sanghyun Lee Aug 20 '14 at 21:32
  • 1
    I tried to set height based on device size. is any other chances to fix max-height in % – phponwebsites Jun 17 '15 at 06:23
12

Use overflow-y with the auto option. This way the scroll bar will not show up until it is needed. Otherwise the scroll bar will display, even if you do not need it to show.

 .my_div {
        width:100px;
        max-height:250px;
        overflow-y:auto;
    }
TV-C-1-5
  • 680
  • 2
  • 13
  • 19
0

just try max-height and do overflow-y:scroll just it

.hidden {
width:100px;
max-height:250px;
overflow-y:scroll;

}
<div class="hidden">

<h5>If the content in this div exceeds 250px it should appear a scroll bar</h5>

</div>
0

For those trying to make a scrollable <table> with Bootstrap 5:

The accepted answer does not work on (or inside) of it.

.dyn-height {
    max-height:250px;
    overflow-y:scroll;
}

You have to add the class to a surrounding div element like this

<div class="dyn-height">
  <table>
    ...
  </table>
</div>
MikhailRatner
  • 452
  • 6
  • 13