text-align

text-align CSS 属性设置块元素或者单元格框的行内内容的水平对齐。这意味着其效果和 vertical-align 类似,但是是水平方向的。

尝试一下

语法

css
/* 关键字值 */
text-align: start;
text-align: end;
text-align: left;
text-align: right;
text-align: center;
text-align: justify;
text-align: justify-all;
text-align: match-parent;

/* 在表格列内基于字符的对齐 */
text-align: ".";
text-align: "." center;

/* 块对齐值(非标准语法) */
text-align: -moz-center;
text-align: -webkit-center;

/* 全局值 */
text-align: inherit;
text-align: initial;
text-align: revert;
text-align: revert-layer;
text-align: unset;

text-align 属性可以按照以下方式之一来指定:

  • 使用关键字值 startendleftrightcenterjustifyjustify-allmatch-parent
  • 仅使用单个 <string> 值,此时另外一个值默认为 right
  • 同时使用关键字值和 <string> 值。

start

如果内容方向是左至右,则等于 left,反之则为 right

end

如果内容方向是左至右,则等于 right,反之则为 left

left

行内内容向左侧边对齐。

行内内容向右侧边对齐。

center

行内内容居中。

justify

文字向两侧对齐,对最后一行无效。

justify-all 实验性

justify 一致,但是强制使最后一行两端对齐。

match-parent

inherit 类似,区别在于 startend 的值根据父元素的 direction 确定,并被替换为恰当的 leftright 值。

<string> 实验性

应用在单元格时,指定单元格内容相对于哪个字符对齐。

无障碍考虑

对于有阅读障碍等认知问题的人来说,对齐的文本产生的单词之间的间距不一致可能会出现问题。

形式定义

初始值start, or a nameless value that acts as left if direction is ltr, right if direction is rtl if start is not supported by the browser.
适用元素block containers
是否是继承属性yes
计算值as specified, except for the match-parent value which is calculated against its parent's direction value and results in a computed value of either left or right
Animation typediscrete

形式语法

text-align = 
start |
end |
left |
right |
center |
justify |
match-parent |
justify-all

示例

开始处对齐

HTML

html
<p class="example">
  Integer elementum massa at nulla placerat varius. Suspendisse in libero risus,
  in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque.
  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
</p>

CSS

css
.example {
  text-align: start;
  border: solid;
}

结果

文本居中

HTML

html
<p class="example">
  Integer elementum massa at nulla placerat varius. Suspendisse in libero risus,
  in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque.
  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
</p>

CSS

css
.example {
  text-align: center;
  border: solid;
}

结果

使用“justify”的示例

HTML

html
<p class="example">
  Integer elementum massa at nulla placerat varius. Suspendisse in libero risus,
  in interdum massa. Vestibulum ac leo vitae metus faucibus gravida ac in neque.
  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
</p>

CSS

css
.example {
  text-align: justify;
  border: solid;
}

结果

规范

Specification
CSS Logical Properties and Values Level 1
# text-align
CSS Text Module Level 3
# text-align-property

浏览器兼容性

BCD tables only load in the browser

参见