Skip to main content

A “new direction” in the struggle against rightward scrolling

By Emerson Loustau

Published on May 19th, 2020

Topics

A menu drawer slides in from the left side of the screenThe other day I was building a responsive website with a navigation menu that slides into view from the left when you click the menu button.

I was about to head off to the pub, but then I learned the menu was supposed to slide in from the right side instead.

No big deal. With a few lines of CSS I can set the default position off the right edge…

An element positioned off-screen to the right causes scrollingBut oh no! An element off the right edge of the screen will cause horizontal scrolling.Footnote 1 This is not cool.

My first thought was to reach for trusty old overflow-x:hidden and be on my way. But there’s a few common situations where this won’t work:

  • Some of the many beloved clearfix solutions for containing floats use overflow:auto;
  • If any of the child elements are position:sticky; they will stop sticking if their parent overflow value is anything other than visible. This is explained in this Stackoverflow answer.
Darn. Now what? I wish I could force the right side of the screen to behave like the left side. Well, it turns out we can! The origin of the scrollbar can be reversed with the lesser-known CSS direction property, which is used to set the direction that text content flows.

body,
html {
direction: rtl;
}
body * {
direction: ltr;
}
Code language: CSS (css)

The first rule switches the text direction of the root node and the body to right-to-left.Footnote 2 This also means the origin of the scrollbar starts from the right, expanding to the left. These are the elements that were previously being overflowed by that right-sided menu. But now they no longer care about elements hidden “behind” them on the right side.

Setting direction to rtl will also reverse the default alignment of text, and English looks funny flowing from right to left. So, the next rule resets all children of the body element back to the default left-to-right text direction.

I have not used this hack in production yet, nor have I done extensive cross-browser testing yet. If you have good or bad experiences with this technique I’d love to hear about it.

Footnotes

  1. If you are building this same experience for a right-to-left language like Arabic, this problem will be reversed and elements positioned to the left will cause scrolling.  Return to the text before footnote 1
  2. In this example, the rule is applied to both the body and the html tag because historically different browsers responded differently when child elements exceeded the viewport width. This issue is explored in more depth in various answers to this Stackoverflow question. Various aspects of body overflow are also discussed in this article Return to the text before footnote 2