How to center elements with writing-mode: vertical-rl
writing-mode: vertical-rl; is
used to create vertical writing layouts, but be careful how you center elements, especially in Firefox. The usual margin-left: auto;
and margin-right: auto;
do not work as intended for vertical writing, so a different method must be used.
1. Why can’t margin: auto;
center the text?
If you use writing-mode: vertical-rl;
for vertical writing, margin-left: auto;
and margin-right: auto;
may not work as in normal horizontal writing. This is because the automatic margin
adjustment does not work as expected for vertical writing. This problem is especially noticeable in Firefox.
2. Workaround
There are two recommended ways to center vertically aligned text
Method 1: Use display: inline-block;
and text-align: center;
.
Set text-align: center;
on the parent element and apply display: inline-block;
on the child elements. This will center the text.
.parent {
text-align: center; /* center the parent element */
}
.child {
writing-mode: vertical-rl;
display: inline-block; /* block the display of child elements */
}
Method 2: Use Flexbox
Another method is to center elements using Flexbox, which is very useful for centering vertically written content because of its flexibility for vertical layouts.
.parent {
display: flex;
justify-content: center; /* horizontal centering */
align-items: center; /* vertical centering */
}
.child {
writing-mode: vertical-rl;
}
In this method, the parent element acts as a Flex container and centers the child element, so that vertical text is also displayed in the intended position.
3. Usage Examples and Recommended Situations
Flexbox is powerful for centering in responsive design and complex layouts, but for simple text centering, the combination of text-align: center;
and inline-block
is easy and effective. It is advisable to use both depending on the situation.
Conclusion
When centering text in vertical writing mode writing-mode: vertical-rl;
, it is effective to use inline-block and
text-align: center;
or Flexbox instead of margin: auto;
. This will ensure compatibility between browsers and still achieve the expected layout.