You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:45:28