i have list with a previously unknown number of elements
i need to apply padding between scroll and content only if list is overflown
<div class="list">
<div class="item">1</div>
<div class="item">many items or 1</div>
</div>
.list {
padding-right: 10px // i need apply this only if scroll apeared
max-height: 40px
overflow: auto
}
I'm not sure if that's possible with CSS, but you can do it with JS, checking it like element.scrollHeight > element.clientHeight
.
For example:
const listElement = document.querySelector('.list');
//OR window.addEventListener('resize', () => applyStylesToList());
new ResizeObserver(() => applyStylesToList).observe(listElement);
applyStylesToList();
function applyStylesToList() {
const hasScroll = isScrollbarVisible(listElement);
listElement.style.paddingRight = hasScroll ? '10px' : '0';
}
function isScrollbarVisible(element) {
return element.scrollHeight > element.clientHeight;
}
.list {
max-height: 40px;
overflow: scroll;
}
<div class="list">
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
</div>