When creating a web application in western countries, we want to read it from the left-to-right and from top-to-bottom.
Once you want to support languages that are read right-to-left, there are some things we need to configure to make the frontend work for all text directions.
Set the attribute
The global dir attribute can be used on all markup elements to indicate the text direction. We can set three values:
-
dir='ltr'
: text direction left-to-right, ie English. -
dir='rtl'
: text direction right-to-left, ie Arabic. -
dir='auto'
: text direction auto, the user agent decides.
The dir
attribute is inherited and can be overwritten.
When we want to set text direction dynamically depending on the used language or a configuration, it is helpful to write a service that holds the current text direction, so that this value can be used wherever needed.
export class TextDirectionService {
public currentTextDirection = TextDirection.RTL;
public constructor(public store: Store<AppState>) {}
public get currentTextDirection$(): Observable<TextDirection> {
return this.store.pipe(selectCommonTextDirection);
}
public setCurrentTextDirection(currentTextDirection: TextDirection): void {
this.currentTextDirection = currentTextDirection;
this.store.dispatch(commonUpdateTextDirection({ updateTextDirection: currentTextDirection }));
}
}
Once the service is in place you can set the current text direction, wherever you need it.
<div class="content" [dir]="currentTextDirection">
<!-- content -->
</div>
Style the elements
Now the text direction changes, depending on the set dir
attribute value.
When we use padding, margin, flex-direction or similar properties to style our app, we need to make some styling adjustments, if the text direction is changed.
.content {
display: flex;
&[dir='ltr'] {
flex-direction: row;
border: 1px solid blue;
}
&[dir='rtl'] {
flex-direction: row-reverse;
border: 1px solid red;
}
}
Handle exceptions
Sometimes we need to use a different text direction for part of the text. For example if we use proper names somewhere in the text.
In that case we can use the bi-directional isolation <bdi>
HTML5 element.
This is similar to the bi-directional overwrite <bdo>
HTML element. The difference is that the <bdo>
reverses the direction. This may lead to unwanted behaviour, so it is more error prune to use the <bdi>
tag.
Native speaker check
When everything is adjusted — generally we want to have everything mirrored — it is always a big win to have a native speaker to check and test the app.
Top comments (1)
just stumbled upon this gold nugget of knowledge, good lord! Totally flipped my worldview left-to-right, ykwim