如何让HTML中右对齐文本与左侧最长文本的右边界对齐?
实现日期与最长左对齐文本右边界对齐的简单方案
当然可以实现,最简单的方式是用一个行内块容器把需要对齐的三个文本元素包裹起来,让容器宽度由内部最长的内容决定,这样右对齐的日期就会和最长文本的右边界对齐。
修改后的代码如下:
<!DOCTYPE html> <html> <style> .text-container { display: inline-block; /* 容器收缩至内容最大宽度 */ } p.date{ text-align: right; } </style> <body> <h2>Some basic HTML</h2> <div class="text-container"> <p class="date"> 5th of January </p> <p>This text element is aligned left by default.</p> <p>This is the second text. It would be nice to have the date aligned with the right end of the text. <br> This time the second text is a little longer but it might be the other way around next time. </p> </div> </body> </html>
原理说明
display: inline-block让容器的宽度自动适配内部最长的文本内容,而非占满整个父容器宽度- 日期元素的
text-align: right基于收缩后的容器宽度生效,自然与最长左对齐文本的右边界对齐 - 无论哪段左对齐文本更长,容器都会自动调整宽度,日期始终和最长文本的右边缘保持对齐
内容的提问来源于stack exchange,提问作者Peter Frey
相关产品推荐
相关产品推荐

