需要实现单效果
实现两端对齐,首相想到到到是justify,但justify对最后一行无效,通常这样的排版对整段文字是极好的,我们并不希望当最后一行只有两个字时也两端对齐,毕竟这是不便于阅读的,那么当我们只有一行文本,但要实现单行文本两端对齐怎么解决?
方法一:
属性text-align-last,该属性定义的是一段文本中最后一行在被强制换行之前的对齐规则。
span:first-child{ text-align: justify; text-align-last: justify; display: inline-block; width: 100px; } span:nth-child(2){ padding-right:15px; }
不过该属性有兼容性问题,大家可以根据情况决定实现方式,想了解更多关于text-align-last的说明。
参见https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-align-last
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title></title> 8 <style> 9 span:first-child{ 10 text-align: justify; 11 text-align-last: justify; 12 display: inline-block; 13 width: 100px; 14 } 15 span:nth-child(2){ 16 padding-right:15px; 17 } 18 </style> 19 </head> 20 <body> 21 <ul> 22 <li> 23 <span>姓名</span> 24 <span>:</span> 25 <span>哈密瓜</span> 26 </li> 27 <li> 28 <span>出生年月</span> 29 <span>:</span> 30 <span>2019-07-04</span> 31 </li> 32 <li> 33 <span>性别</span> 34 <span>:</span> 35 <span>女</span> 36 </li> 37 </ul> 38 </body> 39 </html>
方法二:
根据justify对最后一行无效,我们可以新增一行,使该行文本不是最后一行,
span:first-child{ display: inline-block; width: 100px; text-align: justify; vertical-align: top; } span:first-child::after{ display: inline-block; width: 100%; content: ''; height: 0; }
完整代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title></title> 8 <style> 9 span:first-child{ 10 display: inline-block; 11 width: 100px; 12 text-align: justify; 13 vertical-align: top; 14 } 15 span:first-child::after{ 16 display: inline-block; 17 width: 100%; 18 content: ''; 19 height: 0; 20 } 21 span:nth-child(2){ 22 padding-right:15px; 23 } 24 </style> 25 </head> 26 <body> 27 <ul> 28 <li> 29 <span>姓名</span> 30 <span>:</span> 31 <span>哈密瓜</span> 32 </li> 33 <li> 34 <span>出生年月</span> 35 <span>:</span> 36 <span>2019-07-04</span> 37 </li> 38 <li> 39 <span>性别</span> 40 <span>:</span> 41 <span>女</span> 42 </li> 43 </ul> 44 </body> 45 </html>