overflow:scroll and The Right Padding Problem — A CSS Only Solution

Check out Bruno Fassino’s excellent demo and explanation.

The Problem

Seriously, look at this demo:

  • you have a parent div with overflow:scroll and some padding

  • inside this, you have overflowing children, either with a greater width than the parent or position:absolute

The browser won’t add right padding when you scroll to the end.

The CSS Only Solution

If you’re using absolute children, you’re probably already simulating padding on the top, left and bottom of the parent by adding margin to the children. But, annoyingly, browsers ignore the right margin.

The key is to simulate this margin using an extra element that the browser can’t ignore. With CSS pseudo-elements we can attach an invisible, 1px high block to the righthand side of each child. Then, we simply give this a width equal to the padding we want to simulate.

Using Nothing but CSS

Replace 2rem with a padding of your choice!

.child:after {
  content: "";
  display: block;
  position: absolute;
  right: -2rem;
  width: 2rem;
  height: 1px;

If you know the rightmost child ahead of time, you can save the browser some work by targeting only that element. This is not always easy with position:absolute as the :last-child is not necessarily the rightmost!

An Experiment

I've started a newsletter. A few links to good ideas and interesting stories, in your inbox, every so often. Sound good?