css3 文本两端对齐

文本排版时,尤其在中英文混排,要显得整齐,两端对齐是比较常见的需求。

这时候需要用到 CSS3 两端对齐属性 text-align: justify;

示例

example.html

源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本两端对齐</title>
<style type="text/css">
div {
width: 326px;
border: 1px solid #CCC;
color: #666;
line-height: 1.6em;
}

/**核心代码**/
.justify {
text-align: justify;
text-justify: distribute;
}

.justify-last {
width: 326px;
text-align: justify;
text-justify: distribute-all-lines;
/*ie6-8*/
text-align-last: justify;
/* ie9*/
-moz-text-align-last: justify;
/*ff*/
-webkit-text-align-last: justify;
/*chrome 20+*/
}

@media screen and (-webkit-min-device-pixel-ratio:0) {

/* chrome*/
.justify-last:after {
content: ".";
display: inline-block;
width: 100%;
overflow: hidden;
height: 0;
}
}
</style>
</head>

<body>
<h3>没使用文本两端对齐</h3>
<div>
<p>我们都知道1个全角中文字符占2个英文字符长度,所以在一篇文章中如果有中英文混排,那么一个段落难免会出现参差不齐的现象。为了让段落更整齐,我们可以在CSS中给文本添加个两端对齐的属性,这样不管每一行字符多少都可以显得很整齐。
</p>
<p>CSS property to define how text should be justified when text-align: justify is set.</p>
</div>

<h3>文本两端对齐</h3>
<div class="justify">
<p>我们都知道1个全角中文字符占2个英文字符长度,所以在一篇文章中如果有中英文混排,那么一个段落难免会出现参差不齐的现象。为了让段落更整齐,我们可以在CSS中给文本添加个两端对齐的属性,这样不管每一行字符多少都可以显得很整齐。
</p>
<p>CSS property to define how text should be justified when text-align: justify is set.</p>
</div>

<h3>文本最后一行两端对齐</h3>
<div class="justify-last">
<p>我们都知道1个全角中文字符占2个英文字符长度,所以在一篇文章中如果有中英文混排,那么一个段落难免会出现参差不齐的现象。为了让段落更整齐,我们可以在CSS中给文本添加个两端对齐的属性,这样不管每一行字符多少都可以显得很整齐。
</p>
<p>CSS property to define how text should be justified when text-align: justify is set.</p>
</div>

</body>

</html>

效果:

源码为早期收集,不知出处。

兼容性

Can I use

两端布局可参考文章

张鑫旭大佬的文章:利用 display:inline-block/text-align:justify 实现两端布局

本站文章:css3 flex居中布局,最后一行如何居左排版

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-03-15/css3-text-justify/

如果您觉得文章不错,可以点击文章中的广告支持一下!