Creation of RTL CSS is quite an important process in front-end web development, necessary to make the design comply with the RTL standards. This process involves the substitution of margin-left by margin-right, float: left by float: right… and so on.
Luckily, this job can be done by Grunt with the help of grunt-css-flip bundle, which creates a "reflection" of the CSS file. You can learn the basics of Grunt in the following article. So, let’s get started!
Installing and configuring grunt-css-flip:
1. Install and configure Grunt.
2. Install grunt-css-flip bundle:
npm install grunt-css-flip --save-dev.
3. Create Gruntfile.js.
Let’s analyze the following example of Gruntfile.js file:
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { css: { files: '**/*.css', tasks: ['cssflip:my_target'] }, }, cssflip: { my_target: { options: {}, files: { 'css/styles-rtl.css': 'css/styles.css', } } }, concurrent: { options: { logConcurrentOutput: true }, dev: { tasks: ["watch:css"] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-concurrent'); grunt.loadNpmTasks('grunt-css-flip'); grunt.registerTask('default',['concurrent:dev']); }
Pay attention on this part of the code
cssflip: { my_target: { options: {}, files: { 'css/styles-rtl.css': 'css/styles.css', } } },
Files: here we set the files that should be reflected (you can specify a few files and separate them by comma). Files are defined as: ‘ rtl file name’: ‘file name for which rtl copy must be created’.
Options: here we indicate whether RTL file should be compressed or not (compress parameter, default false value), and set margins for CSS (indent parameter, default value and 2 hiatuses).
4. Run Grunt
From this moment, Grunt will monitor chosen CSS files (in example given it’s css/styles.css) and create the relevant reflected files.
Comments and Specifications :
Grunt-css-flip can be used together with Compass, where Compass generates CSS with sass, and Grunt monitors changes in the CSS files. If they were changed, it would run grunt-css-flip. Grunt-css-flip can be also used with other bundles, where, for instance, Grunt will validate sass/less code (grunt-scss-lint bundle). If the check was over, it would generate CSS (grunt-sass bundle), add prefixes (grunt-autoprefixer bundle) and also generate RTL CSS files (grunt-css-flip bundle).
Here are some things to be aware about when using automatic reflection:
- There is not yet full support for flex, that’s why flex-direction won’t be reflected.
- You should also be very attentive to centering:
margin-left: 50%;
transform: translate(-50%);
Since margin-left will be reflected in margin-right and transform won’t be changed, element in RTL won’t change respectively.
References:
Repository - https://github.com/twbs/grunt-css-flip
Good luck in your coding!