overflow-y auto strange behavior: when scrollbar is visible, it sometimes causes content to shrink, and sometimes not

129 Views Asked by At

I'm trying to show the list of errors to the user inside absolute positioned DIV. Sometimes there will be only a few of these errors, but sometimes there could be tens of them. I want to keep the DIV as small as possible (both width and height), but when the height exceeds some predefined value, scrollbar should appear.

Unfortunately, when using overflow-y: auto, showing the scrollbar makes the error lines to wrap, because they were using as much width as possible, and I'd like to avoid this wrapping.

I have created JS fiddle to simulate this issue with minimal code, but to my surprise, I noticed that while refreshing the fiddle page shows the result with wrapped text that I want to avoid (let's name it result 1), clicking Run works differently - it looks like container DIV is expanded and scrollbar doesn't cause contents to reflow (result 2)... The same happens when page is reloaded, and then result pane is resized. I have no idea why it works like this, and would gladly find this out.

I reproduced the snippet below, and I see that running it shows the result 1, but reloading the snippet frame (e.g. right click and 'Reload frame' in Chrome), display result 2.

Any ideas why, and what can I do to achieve result 2 consistently?

Btw - button was added for some testing, but is not really relevant...

Thanks!

$('#b1').click(function() { $('.o2').toggleClass('hiddenScroll'); });
.o {
  position: absolute;
  border: 1px solid blue;
  max-height: 50px;
  padding: 5px;
  z-index: 1;
  overflow-y: auto;
}

.hiddenScroll {
  overflow-y: hidden;
}

.o1 {
    top: 40px;
}

.o2 {
  top: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='b1'>toggle scroll</button>

<div class='o o1'>
    <div>aaa bbb ccc ddd eee</div>
    <div>aaa bbb ccc ddd eee</div>
</div>

<div class='o o2'>
    <div>aaa bbb ccc ddd eee</div>
    <div>aaa bbb ccc ddd eee</div>
    <div>aaa bbb ccc ddd eee</div>
    <div>aaa bbb ccc ddd eee</div>
</div>

0

There are 0 best solutions below