i have list with a previously unknown number of elements
i need to apply padding between scroll and content only if list is overflown
html
<div >
<div >1</div>
<div >many items or 1</div>
</div>
css
.list {
padding-right: 10px // i need apply this only if scroll apeared
max-height: 40px
overflow: auto
}
CodePudding user response:
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 >
<div >item</div>
<div >item</div>
<div >item</div>
</div>
CodePudding user response:
I was able to get the padding to show after a 3rd div is entered into your list. It does require some vanilla JavaScript to do it this way though. Hope this helps!
let list = document.querySelector(".list");
function moreThan() {
if (list.childElementCount >= 3) {
list.style.paddingRight = "10px";
}
}
list.addEventListener("overflow", moreThan());
.list {
/* padding-right: 10px; */
max-height: 40px;
overflow: auto;
}
<div >
<div >1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
<div >many items or 1</div>
</div>