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. 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;
}

The first rule switches the text direction of the root node and the body to right-to-left. 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.



Source link

Write A Comment