Question:
There is a scroll bar:
#parent {
height: 200px;
width: 300px;
overflow-y: auto;
}
#child {
height: 500px;
width: 100%;
background: teal;
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f6f5f3;
}
::-webkit-scrollbar-thumb {
background: #c1c1c1;
}
<div id="parent">
<div id="child"></div>
</div>
I want to make sure that there is a distance of 2px
between the scrollbar and the content ( #child
block). Essentially I want to write ::-webkit-scrollbar { margin-left: 2px; }
. It doesn't work that way. Tried to add padding-right: 2px
to the element #parent
, but then if the scroll bar is not present (ie, block #child
little content (in this example the height #child
fixed, but in a real project depends on the contents)), there will be extra 2px
empty places. How to add 2px
between scrollbar and #child
block?
Update:
The #parent
block has a property overflow-y: auto;
… That is, whether the scrollbar appears or not depends on the height of the #child
block. In the example, the #child
height #child
fixed, but in a real project it depends on the content (there is dynamically loaded text, a lot of text => a scrollbar will appear, little text => will not appear). This all means that if there is no scroll bar, then the decision should not affect the display. That is, you want to add 2px
free space between the content and the scrollbar if there is a scrollbar, and not add anything if it is not.
Answer:
#parent { height: 200px; width: 300px; overflow-y: auto; } #child { height: 500px; background: teal; } ::-webkit-scrollbar { width: 10px; // 8px (ширина полосы прокрутки) + 2px (расстояние между полосой прокрутки и контентом) } ::-webkit-scrollbar-track { background: #f6f5f3; } ::-webkit-scrollbar-thumb { background: #c1c1c1; border-left: solid 2px #fff; }
<div id="parent"> <div id="child"></div> </div>