弃用 px,拥抱 ch
Death to px, long live ch

原始链接: https://shkspr.mobi/blog/2026/08/death-to-px-long-live-ch/

网页设计中的“像素”往往具有误导性,因为它们代表的是感知单位,而非固定的物理点。在现代高密度屏幕上,一个 CSS 像素可能跨越多个硬件像素,而厘米等度量单位也几乎无法与物理现实对齐。 为了确保在不同设备上都能获得最佳的可读性,作者主张摒弃死板的基于像素的布局。相反,他们利用 `ch`(字符宽度)和 `ex`(小写字母高度)等相对单位。通过基于文本尺寸而非屏幕百分比或绝对像素来设置布局约束,无论用户的显示器如何,元素都能保持比例平衡。虽然作者指出基于像素的设计并非“错误”,但他们建议采用相对单位可以创造出更灵活、以人为本的阅读体验。

```Hacker News最新 | 过往 | 评论 | 提问 | 展示 | 招聘 | 提交登录 舍弃 px,拥抱 ch (shkspr.mobi) 11 点,由 Brajeshwar 发布于 37 分钟前 | 隐藏 | 过往 | 收藏 | 1 条评论帮助 microflash 3 分钟前 [–] 我发现 ch 和 ex 单位深受拉丁字符影响。它们在处理非拉丁字符时会产生奇怪的结果,导致出现“魔术数字”。但这个概念确实很扎实:如果你想要相对于文本的间距,请使用它们。回复 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:```
相关文章

原文

Pixels are a lie. Even if you think you're drawing something with "pixel perfect" accuracy, your monitor is lying to you. There is no grid of platonically perfect squares.

In CSS, pixels are a double lie:

Note that 1px doesn't necessarily equal one physical device pixel. On HD displays, it may span multiple physical pixels. Similarly, 1cm in CSS often doesn't correspond to one hundredth of SI meter. On a large TV screen, it typically is longer than that. The lengths are perceptual: 16px looks roughly the same on a phone, laptop, or TV screen at typical viewing distance.

This blog is primarily text based. I want the width of the text to be readable for the average human. So, rather than setting the main width to be a percentage of the screen, I set it based on character width using the ch unit - which isn't exactly a character but good enough for my purposes:

 CSS--width-content: min(75ch, 100%);

main {
   max-width: var(--width-content);
}

When it comes to padding and margins, the same is true. If I want a gap around an element, I want that gap to be in proportion to the text inside it.

For widths, it makes sense to re-use the ch unit. I want the gap to be in proportion to the text.

But for height, perhaps it doesn't make sense to express vertical distance on character width? In which case the ex unit can be used. It is the size of a typical lower-case letter.

Just like my idea to eliminate CSS classes from my HTML, it's possible to go too far with this. I haven't changed every reference from px to ch, I'm just experimenting to see if it works.

There's nothing wrong, immoral, or evil about using px - or any other measure unit. Using ch and ex fit with my particular proclivities.

联系我们 contact @ memedata.com