How can I add right padding (for example 8px) to my element only if the vertical scrollbar is visible? I want to avoid adding standard padding to maintain symmetry of elements. In my case, I am using overflow-y
as auto
and column flexbox.
I am aware that I can compare scrollHeight
and clientHeight
to determine the visibility of the vertical scrollbar. However, I want to achieve this without using JavaScript, only with CSS properties. I have tried to find some CSS properties like scroll-padding-right
or scroll-margin-right
, but it seems they do not work as I expected based on their names. I also attempted to add a left margin to the scrollbar, scrollbar thumb, scrollbar track, etc., but I was unable to achieve my goal.
Is it possible to achieve scrollbar padding using only CSS?
Thanks in advance.
With CSS only that's not possible to select content with overflow (even though it has been discussed [selectors-5] Proposal for pseudo-selector :overflowed-content but it would have caused circular definitions).
But you can add margin to the scrollbar (selectors ::-webkit-scrollbar
, ::-webkit-scrollbar-track
and ::-webkit-scrollbar-thumb
) with box-shadow
and border
properties.
See solutions here: How do I add a margin to a CSS webkit scrollbar? [closed]
.scroller {
width: 300px;
height: 100px;
overflow-y: auto;
}
::-webkit-scrollbar {
width: 24px;
}
::-webkit-scrollbar-track {
box-shadow: inset 0 0 10px 10px #aeaeae;
border-left: solid 10px transparent;
border-top: none;
border-bottom: none;
border-right: solid 10px transparent;
}
::-webkit-scrollbar-thumb {
box-shadow: inset 0 0 10px 10px #1496ce;
border-left: solid 10px transparent;
border-top: none;
border-bottom: none;
border-right: solid 10px transparent;
}
<div class="scroller">
Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion
daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens
corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts
fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber
earthnut pea peanut soko zucchini.
</div>