PAYATHON 2026

如何让 position: absolute 的 span 按基线或 cap 高度对齐?

数据小陈

不要让 bottom:0/top:0 直接负责字形对齐。绝对定位对齐的是元素的 margin box,不是字形 baseline 或 cap 高度。CSS 的 text-box-trim 和 text-box-edge 可以按 cap、alphabetic 裁切行盒,再用 top:0/bottom:0 让裁切后的边贴住容器。

实现代码

<!DOCTYPE html>
<div class="container">
  <span class="bottom-left">X</span>
  <span class="top-right">X</span>
</div>
.container {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid currentColor;
}

.bottom-left {
  position: absolute;
  left: 0;
  bottom: 0;
  line-height: 1;
  text-box-trim: trim-end;
  text-box-edge: cap alphabetic;
}

.top-right {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 1;
  text-box-trim: trim-start;
  text-box-edge: cap alphabetic;
}

.bottom-left 只裁底边,底边用 alphabetic,所以盒底更接近 baseline;.top-right 只裁顶边,顶边用 cap,所以盒顶更接近 cap 高度。line-height:1 只是减少默认行高带来的干扰,真正修正字形边的是 text-box-*。

为什么 calc(1em - 1lh) 不稳

1em 是字号,1lh 是行盒高度,它们都不是字体的 ascent、descent 或 cap height。不同字体即使字号一样,ascent、descent、半行距和 cap height 也可能不同,所以固定 calc 只能碰巧适配某一种字体。

兼容性和回退

text-box-trim/text-box-edge 属于较新的 CSS 文本裁切能力,发布前应检查目标浏览器。若不支持:

  1. 用 @supports (text-box-trim: trim-both) { ... } 把新写法放在支持分支;
  2. 旧浏览器用 Canvas TextMetrics 或字体度量数据计算 top/bottom 偏移,或者把文字放进 SVG/Canvas 中按 baseline 绘制;
  3. 不要寄希望于固定 em、lh 偏移在所有字体下一致。

注意

  • span 作为绝对定位元素会被“块化”;需要时显式写 display:block 更清楚。
  • 容器必须保留 position: relative,否则绝对定位会参照其他包含块。
  • 如果字体本身有 overshoot 或特殊字形,cap/alphabetic 是字体度量值,不一定等于墨迹像素边缘。

备注:内容仅供参考。