Sub topic 2
Writing mode and direction
This chapter assumes you know the CSS box model, the HTML lang and dir attributes, and that some languages run right to left (RTL) or top to bottom. Two settings decide how a page flows: writing-mode and direction. Every logical property depends on them.
Two settings, two jobs
writing-mode decides whether lines of text run horizontally or vertically. It also decides which way new lines stack.
direction decides which way text runs along a line: ltr (left to right) or rtl (right to left).
| `writing-mode` value | Lines run | Lines stack |
|---|---|---|
| `horizontal-tb` (default) | Horizontally, set by `direction` | Top to bottom |
| `vertical-rl` | Top to bottom | Right to left |
| `vertical-lr` | Top to bottom | Left to right |
English, Arabic and Hebrew all use horizontal-tb. They differ only in direction. Traditional Japanese and Chinese often use vertical-rl. Mongolian uses vertical-lr.
Setting them in a page
Set direction in HTML with the dir attribute, not with CSS. The attribute still works when styles fail to load. It also tells assistive technology and the bidirectional text algorithm what the content is.
<p dir="rtl" lang="ar">مرحبا بالعالم</p>
<p dir="ltr" lang="en">Hello, world</p>
<p dir="auto">User-submitted text of unknown language</p>Use dir="auto" for user-generated content. The browser picks the direction from the first strong character it finds.
Set writing-mode in CSS, because HTML has no attribute for it:
.vertical {
writing-mode: vertical-rl;
inline-size: 20rem;
block-size: 10rem;
}In a vertical mode, lines run down the page. The element's height is therefore the length along the line, and inline-size sets that height. The next chapter explains why.
Direction inside vertical text
direction still works in vertical modes. direction: rtl with writing-mode: vertical-rl makes the text run from bottom to top. Most vertical text keeps ltr, which means top to bottom.
Common errors
- Using
direction: rtlto flip a layout. It only changes the inline direction. Thedirattribute is the right tool, and it also handles bidirectional text correctly. - Setting
directionin CSS and leavingdiroff the HTML. Browsers and assistive technology then lose information about the content. - Expecting
widthandheightto follow the writing mode. They stay physical. After you switch to a vertical mode, awidththat used to control line length now controls how many lines fit. - Confusing
writing-modewith rotation.transform: rotate()turns the pixels.writing-modechanges how the text is laid out, so lines wrap and sizes resolve differently.
Exercise
Which writing-mode value gives lines that run top to bottom and stack from right to left, and which property would make those lines run bottom to top?
Show answer
writing-mode: vertical-rl gives top-to-bottom lines that stack from right to left. Adding direction: rtl makes the lines run bottom to top.