Last Updated: February 25, 2016
·
2.952K
· lurx

Writing smart LTR/RTL CSS with SASS

There are multiple ways to approach converting your site to RTL. Manually converting the file, using plugins, scripts etc, or - writing smart code. I don't mean that your code will think for you, just that one code will create two files for you, that are manageable, maintainable and easy to look at.

What you need to know before we start.

This post is all about how to create code in SASS that will compile your CSS for LTR and RTL at the same time.
I will do my best to make it clear, but basic SASS knowledge will make it easier to understand.
I will not explain how to install SASS or how to get it to work for you. You can read that here.

Lastly: all naming conventions presented here are merely suggestions.

First, let's talk architecture

There are two ways you can approach to loading your CSS files:

  1. A file dedicated to all styles (LTR) and a file with specific overwrites for RTL.

    <link type="stylesheet" src="style-ltr.css">
    <link type="stylesheet" src="style-rtl.css">

  2. A single file for each direction, containing the entire CSS, with differences per direction.

    <link type="stylesheet" src="style-rtl.css">

Next up - Basic setup

You will need to set up two main SCSS files:style-ltr.scss and style-rtl.scss.

//style-ltr.scss
@charset "UTF-8";

$text-direction: ltr !default;
/* Partials */
@import 'partials/_navigation';
@import 'partials/_main';
...

and in style-rtl.scss we only need to use 3 lines:

//style-rtl.scss
@charset "UTF-8";

$text-direction: rtl;
@import 'style-ltr';

When your SASS watcher will compile the files to CSS, it will automatically compile them both. now, in your partials, all you need to do is build your rules as you usually would, with a simple if/else condition where you have LTR/RTL. Common rules should be outside the if/else brackets:

.class {
    width: 10em;
    color: #00ccff;
    @if $text-direction == ltr {
        text-align:left;
    } @else {
        text-align:right;
    }
}

This will output two versions of the same rule (in the aforementioned LTR and RTL files):

//LTR
.class {
    width:10em;
    color: #00ccff;
    text-align:left;
}

and

//RTL
.class {
    width:10em;
    color: #00ccff;
    text-align:right;
}

That's all there is to it.

This makes your code very manageable, each rule is in one place and there is no need to look for it in two places to make changes, or maintaining two different files at all times.