I remember having to do this several years ago working on a monolithic C# e-commerce platform. The business gave the team a hard deadline to have an Arabic version of the site working within 3 months. The CSS was written a few years before and providing multi-language support was never part of the original scope. With such a tight-deadline the team did the only things possible... hack the code until it was deemed acceptable.
The command to install
postcss-rtl with yarn/npm is shown below:
If you have a
postcss.config.js file, you can enable the package like so:
With the package enabled, when the CSS is built, a right-to-left version will also be generated.
postcss-rtl will invert each CSS style to work from left-to-right to right-to-left. With some simple configuration, your whole site can be converted quickly, saving your months worth of effort!
First, let us quickly discuss how to write right-to-left CSS. When you want to write CSS to target different text directions, you use the
dir attribute on an element. The
dir attribute sets the base direction of how text is displayed. To enabled right-to-left test on a page you would write this HTML:
There are several approaches on how you would write the CSS, some approaches may include:
Instead of manually having to go through the entire site and change everything, we can get
postcss-rtl to do it for us. This is the overview of how this process will look. When your application compiles, it will call web pack. At some point, web-pack will call
post-css to process the applications CSS and perform any additional tasks. If configured correctly,
post-css will also run
postcss-rtl runs it will also auto-generate additional CSS targeting by automatically adding the 'dir' attribute. For example, take this simple selector:
postcss-rtl runs, if you look within the applications CSS file you will find a new selector that includes 'rtl' and 'ltr':
Armed with these new styles, if you set your pages HTML dir to RTL and reload the page, you should now see that your site's text has flipped. A word of caution,
postcss-rtl is a plug-in which means that it may not look perfect for all languages without any additional custom styling. It will, however, get you a lot further down the path without having to do much. From my experience, we probably saved 4 weeks of effort using this plug-in compared. Having manually go through and write all the CSS is a chore so let
postcss-rtl do the grunt work for you. Happy coding!