Problems with RTL flipping CSS using overrides

Some CSS properties are easier to override for RTL flipping than others.

Easy

Float and clear are very easy. Text-align and text-indent are fine. Any property that is defined with one value is easy to flip.

For example, float can be either left or right.

float: left;

@if $rtl {
  float: right;
  // This will completely override the original rule
}

Shorthand styles are also easy to flip, since all the values will be overridden. Given padding is used:

padding: 1px 2px 3px 4px;

@if $rtl {
  padding: 1px 4px 3px 2px;
  // We can simply swap the left and right values to achieve a clean override
}

Medium

The more tricky ones are left and right. These don’t override cleanly because both can exist simultaneously. Take the following example:

left: 0;

@if $rtl {
  right: 0;
}

The compiled CSS for the LTR stylesheet would look like this:

left: 0;

Fine. However the RTL stylesheet will look like this:

left: 0;
right: 0;

See the problem?

To resolve this, you must replace the LTR value with auto. Auto is the default value for left and right. However this does mean an extra style whenever left or right occurs.

left: 0;

@if $rtl {
  left: auto;
  right: 0;
}

Hard

Any longhand styles such as margin-left, margin-right, border-left, border-right, and so on behave in the same way as left and right. They are slightly harder however, because we cannot simply reset the original value to 0. Take the following example:

margin-left: 10px;

@if $rtl {
  margin-left: 0;
  margin-right: 10px;
}

So here we have swapped the left and right margin and reset the left to 0. However, what if the margin-right was being set elsewhere. We have just reset it to 0 without taking into consideration other styles which may be contributing to the same element. This is something to be careful with.

Impossible

background-position is impossible to flip if a numeric value has been used for the horizontal positioning.

It is very common to use background-position to nudge a background-image across if it is misaligned, however this causes issues if we need a RTL stylesheet.

This is because the functionality to align a background image on the right with an offset is missing from the CSS specification. We cannot say I want to align my background image 5px from the right.

The solution is to always set the horizontal value as left or right, and use padding on a parent container to align the background image.

Lessons

  • Use shorthand where possible
  • Don’t use numeric values for laying out a background-image horizontally
Posted Wednesday, March 6th, 2013 under BBC.

Leave a Reply

*