Toni Toni - 4 months ago 8
jQuery Question

When toggeling overflow property on parent element

The example Fiddle here.

A container with

height:auto
contains items with the
width:100%
. When a button is clicked, the list changes to
height:400px
and
overlow-y:scroll
. When clicked again, the items have no longer
width:100%
. They remain the width as the scrollbar would still be visible.

Is there a css-way of fixing this? I would like to avoid a jquery-hack.

This is what I see on Windows, Chrome 52:

After page load:

After page load

After a first click on Toggle:

After a first click on Toggle

After a second click on Toggle:

After a first click on Toggle

Thank you so much!

?!? Links to jsfiddle.net must be accompanied by code. Okaaayy..?!?

.scroll{
height:400px;
overflow-y:scroll;
}

Answer

This seems to be a bug in Google Chrome. The children element loose their initial width when scrollbar is added however the calculated width has no change when the element is inspected.

As a CSS hack you can hide X-overflow in the container to prevent children from resizing when scroll bar is added.

Be careful this trick may practically fail if the content of items are too long and overflow the container.

$("#toggle-scroll").on("click touchstart", function(){
	$("#list").toggleClass("scroll");
});
#list{
  background-color:#808000;
  width:300px;
  overflow-x:hidden;
}
.item{
  background-color:#555;color:#efefef;
  padding:4px;margin:1px;
}
.scroll{
  height:400px;
  overflow-y:scroll;
}
.btn{
  display:inline-block
  padding:15px;
  margin:15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle-scroll" class="btn">Toggle Scrollbar</button>

<div id="list">

  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>
  <div class="item">Entry XYZ</div>

</div>

Comments