33

I want to target elements which have a visible scrollbar using only CSS. Is this possible without javascript?

For example, If I have 3 divs styled with overflow-y:auto, How do I change the styles for them only when their scrollbar has appeared?

cronoklee
  • 6,482
  • 9
  • 52
  • 80
  • 8
    I don't think this is possible but I'd like to be proved wrong – Jonas Grumann Jun 29 '15 at 11:49
  • I think this is similar to question [link](http://stackoverflow.com/questions/16865167/is-there-a-css-selector-that-will-select-elements-with-overflowing-text), It does not seem possible using CSS only – KAD Jun 29 '15 at 11:50
  • 1
    Not with pure CSS. I know you said no JS, but this might be useful if you change your mind http://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible – Equalsk Jun 29 '15 at 14:12
  • I suppose it wouldn't be possible to style elements depending if there is a scrollbar or not. Consider the scenario where when you have a scrollbar you you alter the height of the elements inside so the scrollbar is removed, then they get to their original height, the scrollbar appears and so on... – xpy Jul 29 '16 at 08:36

3 Answers3

16

CSS does not cover this selection. You need to use JavaScript.

Teo Maragakis
  • 427
  • 4
  • 11
1

With pure CSS I doubt it but it doesn't require a lot of javascript code either, look at this example:

document.querySelectorAll('*').forEach(el => {
  if (el.offsetHeight > document.documentElement.offsetHeight) {
      console.log('I am higher than my father: ', el);
      el.classList.add('higher-class');
  }
});
.higher-class {
  color: red;
}
<div class="container" style="height:50px;">
  <div class="some-child"  style="height:100px;font-size: 5rem">
    Higher element
  </div>
</div>

check

fitorec
  • 4,257
  • 2
  • 24
  • 18
1

It's not possible without javascript

However it only requires a single line of JS to toggle a CSS class on when the scrollbar is visible:

el.classList.toggle("scrollbarOn", el.scrollHeight > el.clientHeight)

Here's a demo:

//toggles a class on an element when the scrollbar is visible:
function updScrollClass(el) {
  return el.classList.toggle("scrollbarOn", el.scrollHeight > el.clientHeight)
}
//changes the height of myDiv every second:
setInterval(function(){
  var myDiv = document.getElementById('myDiv')
  myDiv.classList.toggle('tall')
  updScrollClass(myDiv)
},1000)
#myDiv{ 
  width:150px;
  height:200px;
  overflow:auto;
}

#myDiv.tall{
  height:300px;
}

.scrollbarOn{ 
  background:yellow;
}
<div id='myDiv' class='tall'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc convallis nisl in accumsan porta. Etiam in urna orci. Vestibulum elementum, velit ac vestibulum efficitur, est elit auctor massa, nec porta ante nunc eget tellus. Integer eu ligula felis. 
</div>
cronoklee
  • 6,482
  • 9
  • 52
  • 80