理解 CSS 长度单位

Junior developers who were recently introduced to CSS might be overwhelmed by the sheer number of various length-measuring units available. Someone might say not to use px as absolute units don’t change in responsive design but is that really the case?

刚接触 CSS 的初级开发者可能会被各种长度单位搞得眼花缭乱。有人可能会说不要用 px,因为绝对单位在响应式设计中不会变化,但真的是这样吗?

Let’s have a quick overview on the various units and when they can be useful.

让我们快速浏览一下各种单位及其适用场景。

The Absolute Units

The Absolute Units

px - a pixel is the smallest point that the screen can present. Although with the introduction of retina displays that have a high pixel density, modern day px represents a virtual pixel rather than the monitor’s actual capabilities. This is big news because it means px is no longer absolute. Let’s get back to that later.

px - 像素是屏幕能呈现的最小点。随着高像素密度的 retina 屏幕出现,现代 px 表示的是虚拟像素,而非显示器的真实能力。这很重要,因为这意味着 px 不再是绝对单位。我们稍后再谈。

Retina display has denser pixels

cm, mm, q, in, pc, pt - centimetres, millimetres, quarter-millimeter , inches, picas (1/6 of an inch), and points (1/72 of an inch) are recommended for printing, and not for the screen. The first computer-printer could print dots as small as 1/72 per inch, hence 1pt equals 1 dot for a low-resolution printer. Nowadays, printers can reach 150, 300, 600 or even 1200 points per inch so that’s an indication how small that point can be. Therefore it’s probably smart to use one of the other measuring using or a relative unit to make sure the page is printed as we expect it, regardless of the printer’s resolution.

cmmmqinpcpt - 厘米、毫米、四分之一毫米、英寸、派卡(1/6 英寸)和点(1/72 英寸)推荐用于打印,而非屏幕。第一台电脑打印机每英寸只能打印 1/72 的点,因此 1pt 在低分辨率打印机上等于 1 个点。如今,打印机可达 150、300、600 甚至 1200 dpi,由此可见一个点可以有多小。因此,明智的做法是使用其他度量单位或相对单位,以确保无论打印机分辨率如何,页面都能按预期打印。

print output can have different resolutions

The Relative Units

The Relative Units

% - percentage is relatively easy to understand – it’s relative to the parent. The only issue is – what is considered the parent? It might be an obvious answer unless the item’s position is absolute and then things become slightly trickier.

% - 百分比相对容易理解——它是相对于父元素的。唯一的问题是——什么被视为父元素?答案可能显而易见,除非元素的 position ...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-09-03 21:08
浙ICP备14020137号-1 $访客地图$