text-align: justify

  大家都知道 text-align 属性是规定元素中的文本的水平对齐方式,最常用的值是left、right、center,那么justify是什么呢?

 

  在W3C上是这样介绍的:

    justify 可以使文本的两端都对齐在两端对齐文本中,文本行的左右两端都放在父元素的内边界上。然后,调整单词和字母间的间隔,使各行的长度恰好相等

 

  这段话有点拗口,为了直观点体现出它的特点,所以直接上码上图:

 

css3总结之: text-align: justify  (两端对齐)-编程之家

<p style="width:400px;text-align:left;;margin:20px auto;"><strong style="color:#000;margin-bottom:10px;">text-align: left:</strong></br></br>Nettie Maria Stevens was an early American geneticist. In 1905, she and Edmund Beecher Wilson were the first researchers to independently describe the chromosomal basis of sexNettie在海岸边,退潮时你可徒步走到一些岛屿近处,在潮间带里看见诸如海星、海胆、海带等海洋生物,体验甜蜜的幸福感。或是在天气好时,肩并肩坐在海滩上等待日落晚霞,浪漫满溢。</br></br>浪漫满溢
</p><p style="width: 400px;text-align: justify;margin:20px auto;"><strong style="color:#000;margin-bottom:10px;">text-align: justify:</strong></br></br>Nettie Maria Stevens was an early American geneticist. In 1905, she and Edmund Beecher Wilson were the first researchers to independently describe the chromosomal basis of sexNettie在海岸边,退潮时你可徒步走到一些岛屿近处,在潮间带里看见诸如海星、海胆、海带等海洋生物,体验甜蜜的幸福感。或是在天气好时,肩并肩坐在海滩上等待日落晚霞,浪漫满溢。</br></br>浪漫满溢
</p>

css3总结之: text-align: justify  (两端对齐)-编程之家

 

 

上面的代码很简单,第一个是字体左对齐,另一个是两端对齐,出来的效果是这样的:

 

css3总结之: text-align: justify  (两端对齐)-编程之家

 

 

两种方法放一块比较就可以看出使用了 text-align: justify 文字的两端是对齐的。

 

但是仔细观察一下,发现为了两端对齐,有些文字的间距就被拉开了(第二行的英文)。有时候间隔隔得太大会造成阅读困难,所以如果有需要的情况下用letter-spacing收缩字符间距就可以了。

 

另外, text-align-last:right 可以改变段落的最后一行的对齐方式。但是只有在 text-align 属性设置为 "justify" 时才起作用

 

如果这个方法排版会是怎样的呢?

css3总结之: text-align: justify  (两端对齐)-编程之家

<ul class="justify_list"><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>

css3总结之: text-align: justify  (两端对齐)-编程之家

.justify_list{text-align: justify;text-justify:distribute-all-lines;width: 600px;}
li{width:100px; height:100px;background-color: #0086b3; display: inline-block; list-style:none; }

 

效果如下:

css3总结之: text-align: justify  (两端对齐)-编程之家

 

这时候发现,被挤下来的部分并没有左右两端对齐。

 

经过查询才知道原来是text-align:justify 不处理块内的最后一行文本(包括块内仅有一行文本的情况,这时既是第一行也是最后一行)

 

既然如此,解决方法就简单了:

.justify_list:after {width: 100%;height: 0;margin: 0;display: inline-block;overflow: hidden;content: '';}

 

效果如下:

 

css3总结之: text-align: justify  (两端对齐)-编程之家

 

总体来说实现得还不错。在排版的时候不需要计算每个列表元素间的margin间距,比用float的时候省事很多。