CSS 方向

CSS `direction` 属性用于指定块内文本和布局的基本方向。例如,

h1 {
    direction: rtl;
}

浏览器输出

CSS Direction

在此,`direction: rtl` 将 `h1` 元素中文本的方向更改为从右到左。


CSS 方向语法

`direction` 属性的语法如下:

direction: ltr | rtl | initial | inherit;

这里,

  • `ltr` - 将文本方向设置为从左到右,这是默认值
  • `rtl` - 将文本方向设置为从右到左
  • `initial` - 将属性值设置为默认值
  • `inherit` - 从其父元素继承属性值

方向属性示例

让我们看一个 `direction` 属性的例子:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="style.css" />
  <title>CSS Direction</title>
</head>

<body>
  <div class="numbers original">
      <h2>Original Numbers</h1>
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
  </div>
 
  <div class="numbers ltr">
     <h2>direction: ltr (left-to-right)</h2>
   <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
  </div>

  <div class="numbers rtl">
      <h2>direction: rtl (right-to-left)</h2>
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
  </div>
</body>

</html>
span {
    border: 1px solid blue;
    padding: 2px 4px;
}

/*sets the text direction to left-to-right, default value */
div.ltr {
    direction: ltr;
}

/* sets the text direction to right-to-left */
div.rtl {
    direction: rtl;
}

浏览器输出

CSS Direction Example Description

`rtl` 值适用于从右到左书写的语言,如阿拉伯语或希伯来语,而 `ltr` 用于从左到右书写的语言,如英语。

让我们看一个例子,

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>CSS Direction</title>
    </head>

    <body>
        <div class="english">
            <h2>English Text (left-to-right)</h2>
            <p>This paragraph have the direction to left-to-right.</p>
        </div>
        <div class="arabic">
            <h2>Arabic Text (right-to-left)</h2>
            <p>
                هذه الفقرة باللغة العربية ، لذا يجب الانتقال من اليمين إلى
                اليسار. هذه الفقرة باللغة العربية ، لذا يجب الانتقال من اليمين
                إلى اليسار.
            </p>
        </div>
    </body>
</html>
/*sets the text direction to left-to-right, default value */
div.english {
    direction: ltr;
}

/* sets the text direction to right-to-left */
div.arabic {
    direction: rtl;
}

浏览器输出

CSS Direction Example Description

注意:CSS 属性 `unicode-bidi` 可以与 `direction` 属性结合使用来更改文本的方向。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战