樣式表中處理文字方向有兩個重要屬性:writing-mode 與 text-align。
writing-mode: lr-tb; /* 由左至右、由上而下(預設) */
writing-mode: tb-rl; /* 由上而下、由右至左(直排) */
div { writing-mode: tb-rl; }
text-align: left | right | center | justify;
div { text-align: center; }
在不支援 writing-mode 的年代,直排只能靠一個小技巧:把容器的寬度設成剛好只放得下一個字,讓文字自動逐字換行,視覺上就變成直排了。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>直排列排版實例</title>
<style>
body { text-align: center; }
.shuli {
margin: 0 auto;
width: 20px;
line-height: 24px;
border: 1px solid #333;
}
</style>
</head>
<body>
<div class="shuli">我是直排列排版</div>
</body>
</html>
關鍵在 width: 20px 搭配 line-height: 24px:寬度只夠一個字,行高決定字距。這個做法雖然老派,但在需要相容舊版瀏覽器時仍然管用。
現代專案則建議直接用 writing-mode: vertical-rl(CSS Writing Modes Level 3 的標準寫法),並搭配 text-orientation 控制中英混排時的字母方向,會比壓寬度的 hack 乾淨得多。