Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

ข้อความแนวตั้ง ตัวอักษรแนวนอน ด้วย CSS writing-mode และ text-orientation

CSS Properties writing-mode และ text-orientation ช่วยให้เราแสดงข้อความแนวตั้ง (Vertical Text) แต่ตัวอักษรยังคงอ่านได้แนวนอน (Horizontal Letters) เหมาะสำหรับภาษาเอเชียหรือ Design ที่ต้องการเอฟเฟกต์พิเศษ

Syntax

selector {
  writing-mode: /* value */;
  text-orientation: /* value */;
}

writing-mode Values

Valueทิศทางใช้กับ
horizontal-tbซ้าย→ขวา, บน→ล่าง (Default)ภาษาละติน, อังกฤษ
vertical-rlบน→ล่าง, ขวา→ซ้ายจีน, ญี่ปุ่น, เกาหลี (Traditional)
vertical-lrบน→ล่าง, ซ้าย→ขวามองโกล, ภาษาบางชนิด
sideways-rlบน→ล่าง, ขวา→ซ้าย (หมุน 90°)Special Effects
sideways-lrบน→ล่าง, ซ้าย→ขวา (หมุน -90°)Special Effects

text-orientation Values

Valueพฤติกรรม
mixed (Default)อักขระแนวตั้งอยู่แนวตั้ง, แนวนอนหมุน 90°
uprightทุกตัวอักษรตั้งตรง (Horizontal Letters)
sidewaysทุกตัวอักษรหมุน 90° (Sideways)

ตัวอย่างที่ 1: Vertical Text กับ Upright Letters

<!DOCTYPE html>
<html>
<head>
  <style>
    h4 {
      text-orientation: upright;
      writing-mode: vertical-rl;
      line-height: 3;
      box-shadow: inset 0 0 3px khaki;
    }
  </style>
</head>
<body>
  <h4>Sed nec tortor</h4>
</body>
</html>

ผลลัพธ์: ข้อความ "Sed nec tortor" วิ่งจากบนลงล่าง ตัวอักษรแต่ละตัวตั้งตรงอ่านง่าย

ตัวอย่างที่ 2: หลายบรรทัด Vertical Text ด้วย Flexbox

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      display: flex;
      flex: 1;
    }
    p {
      text-orientation: upright;
      writing-mode: vertical-rl;
      line-height: 3;
      box-shadow: inset 0 0 13px orange;
    }
  </style>
</head>
<body>
  <p>One</p>
  <p>Two</p>
  <p>Three</p>
  <p>Four</p>
</body>
</html>

ผลลัพธ์: คำว่า One, Two, Three, Four วิ่งแนวตั้งเรียงติดกัน (เพราะ body เป็น Flex Container) แต่ละคำอ่านแนวนอนได้

การประยุกต์ใช้งานจริง

1. Table Headers แนวตั้ง (Vertical Table Headers)

th.vertical {
  writing-mode: vertical-rl;
  text-orientation: upright;
  min-width: 40px;
  height: 120px;
  white-space: nowrap;
}

2. Side Labels / Sidebar Text

.side-label {
  writing-mode: vertical-rl;
  text-orientation: upright;
  position: fixed;
  left: 0; top: 50%;
  transform: translateY(-50%);
  font-weight: bold;
  letter-spacing: 2px;
}

3. Creative Typography Design

.vertical-title {
  writing-mode: vertical-rl;
  text-orientation: upright;
  font-size: 5rem;
  font-weight: 900;
  line-height: 1;
  color: transparent;
  -webkit-text-stroke: 2px black;
}

Browser Support

  • writing-mode: Chrome 48+, Firefox 41+, Safari 10.1+, Edge 12+
  • text-orientation: Chrome 48+, Firefox 41+, Safari 10.1+, Edge 79+
  • IE: ไม่รองรับ (ต้องใช้ -ms-writing-mode: tb-rl; แบบเก่า)

คำเตือน

  • ไม่ควรใช้กับเนื้อหายาวๆ (ยากต่อการอ่าน)
  • ต้องทดสอบ Accessibility (Screen Readers อาจอ่านผิดลำดับ)
  • Line-height ต้องตั้งให้มากพอ (เช่น 2-3) ไม่อย่างนั้นตัวอักษรจะทับกัน
  • ร่วมกับ text-combine-upright: digits 2; สำหรับตัวเลข 2 หลักในแนวตั้ง