Motla Motla - 1 year ago 82
CSS Question

Set space/margin all around an absolute <div> which is inside a scrollable <div>

I'd like to set a margin all around a

with a
inside a scrollable
to let some free space between the inside div and the scrollable area boundaries (right and bottom).

I tried something like this but with no luck:

<div style="overflow:scroll">
<div style="position:absolute; margin-right:100px; margin-bottom:100px">DRAG ME</div>

Demo here:

Only the margin-bottom works, and only in Chrome.

You can also imagine that there are other elements inside the scollable div and that they should stay clickable even if they are masked by the margin of the "drag me" element (which should be the case when using CSS margins).

I'm looking preferably for a CSS-only solution that works in Webkit browsers.

Any ideas?

Answer Source

The easiest way to achieve this is to create an invisible CSS ::before pseudo-element that covers the box plus a padding, and to make it transparent to the mouse interactions using the pointer-events property:{
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    padding-right: 100px;
    padding-bottom: 100px;
    pointer-events: none;
    /* background-color: rgba(255,0,0,0.2); // to understand what is going on */

Demo here:

Be warned that it's not working when the box has an overflow property that is not set to visible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download