Kiran Dash
Kiran Dash

Reputation: 4956

Hide scrollbar track for element with no overflow content

I have a wrapper element that could have content overflowing or not. And I am using overflow-y: visible to show the scrollbar on overflow. And I have customised to add a background to the scrollbar track. As you can see from code below.

Expectation: I don't want to see the scrollbar track when there is no overflowing content. (For example: the second wrapper in my code below shouldn't show the track)

.wrapper {
  background: blue;
  margin: 30px;
  width: 100px;
  float: left;
  color: white;
  overflow-y: scroll;
}

#overflow {
  height: 150px;
}

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  background: red;
  border-radius: 11px;
}

::-webkit-scrollbar-thumb {
  background: grey;
  border-radius: 15px;
  box-shadow: 0px 5px 10px rgba(20, 30, 54, 0.8);
}
<div id="overflow" class="wrapper">
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
</div>

<div id="non-overflow" class="wrapper">
No overflow<br/>
No overflow<br/>
No overflow<br/>
</div>

Upvotes: 1

Views: 1580

Answers (1)

Vaibhav
Vaibhav

Reputation: 602

First, set a max-height for the div. This will ensure that the scroll bars should be visible if and only if the height of the div goes beyond the max-height. Then, set overflow-y to auto. This will make sure that when the height of the div goes beyond the max-height then the scrollbars should appear.

I've added an extra div to show the working.

.wrapper {
  background: blue;
  margin: 30px;
  width: 100px;
  float: left;
  color: white;
  overflow-y: auto;
}

#overflow {
  max-height: 150px;
}

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  background: red;
  border-radius: 11px;
}

::-webkit-scrollbar-thumb {
  background: grey;
  border-radius: 15px;
  box-shadow: 0px 5px 10px rgba(20, 30, 54, 0.8);
}
<div id="overflow" class="wrapper">
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
</div>

<div id="overflow" class="wrapper">
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
overflow<br/>
</div>

<div id="non-overflow" class="wrapper">
No overflow<br/>
No overflow<br/>
No overflow<br/>
</div>

Upvotes: 1

Related Questions