Handle Document Direction with a Handy Sass Mixin

George Treviranus
2 min readOct 20, 2019

--

Accounting for document direction can be frustrating. So, with the inspiration of my coworkers, I attempted to implement my own sass mixin to handle rtl formatting.

While some of the CSS spec greatly accounts for document direction (flexbox, for example), much of it (mostly the older bits) doesn’t.

This mixin searches a given property/value pair’s text for “left” or “right” and inverts them to “right” and “left”, respectively. For values, the mixin checks that it’s a string first. If not, the value is skipped and default is returned.

The utility utilizes Hugo Giraudel’s str-replace function, which is essentially the same as JavaScript’s String.replace().

All that said, here’s the mixin:

@mixin set-flow($property, $value) {
$rtl-property: $property;
$rtl-value: $value;
// Check value and invert it @if type-of($value) == string {
@if str-index($value, "left") {
$rtl-value: str-replace($value, "left", "right");
} @else if str-index($value, "right") {
$rtl-value: str-replace($value, "right", "left");
}
}
// Check property and invert it @if str-index($property, "left") {
$rtl-property: str-replace($property, "left", "right");
} @else if str-index($property, "right") {
$rtl-property: str-replace($property, "right", "left");
}
// Return ltr + rtl html:not([dir="rtl"]) & {
#{$property}: $value;
}
html[dir="rtl"] & {
#{$rtl-property}: $rtl-value;
}
}

Using it is simple:

.my-class-name {
@include set-flow("left", 12px);
@include set-flow("text-align", "right")
}

The output:

html:not([dir="rtl"]) .my-class-name {
left: 12px;
text-align: right;
}
html[dir="rtl"] .my-class-name {
right: 12px;
text-align: left;
}

Thanks for reading!

George is a front-end developer and digital designer living in Oakland, California. He is currently between jobs, about to start at ServiceNow on their Design Systems team. Other times, he can be found long boarding, playing video games, or collecting way too many Pokemon cards.

--

--