<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Centered column</title>
<style>
body { font-family: system-ui, sans-serif; color: #111827; }
.column { max-width: 320px; margin-inline: auto; border: 2px dashed #2563eb; padding: 8px; }
.column h2 { text-align: center; margin-top: 0; }
</style>
</head>
<body>
<div class="column">
<h2>Centered title</h2>
<p>This column sits in the middle of the page, but its lines of text start at the same edge, which keeps longer text easy to read.</p>
</div>
</body>
</html>
margin-inline: auto 让有宽度的块居中,text-align 让块里的行居中。盒子的居中方法(用 flexbox、grid 或外边距)在 div 居中页面中有介绍。
align-items: center 负责垂直居中,justify-content: center 负责水平居中,有多行文字时,text-align: center 仍然会让各行彼此居中对齐。line-height 的技巧只适用于已知高度盒子里的单行文字。
text-align 的所有取值
值
效果
start(默认值)
各行从起始边开始:在中文和英文中是左边,在阿拉伯语和希伯来语中是右边
end
各行在结束边结束
center
各行居中
justify
各行拉伸到两边对齐(最后一行除外)
left、right
无论哪种语言,始终靠左或始终靠右
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text-align values</title>
<style>
body { font-family: system-ui, sans-serif; }
p { width: 260px; border: 2px solid #e5e7eb; padding: 4px; }
</style>
</head>
<body>
<p style="text-align: start">start: the default for most text.</p>
<p style="text-align: end">end: lines hug the end edge.</p>
<p style="text-align: justify">justify: the spaces between words stretch so every full line reaches both edges of the box.</p>
<p dir="rtl" style="text-align: start">start in a right to left paragraph</p>
</body>
</html>
优先使用 start 和 end,而不是 left 和 right:在从右到左书写的语言中,它们会自动翻转,就像最后一个盒子展示的那样。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Indent</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 420px; }
.first-line { text-indent: 2em; }
.block { padding-inline-start: 2em; border-inline-start: 3px solid #2563eb; }
.hanging { padding-inline-start: 2em; text-indent: -2em; }
</style>
</head>
<body>
<p class="first-line">text-indent moves only the first line of the paragraph, the way books start a new paragraph. The following lines start at the edge.</p>
<p class="block">padding-inline-start indents every line of the block.</p>
<p class="hanging">A hanging indent: the first line sticks out and the rest is indented, as in a bibliography entry.</p>
</body>
</html>