CSS 基础教程:测量单位

138 阅读3分钟

CSS 基础教程:测量单位

Hudson 译 原文

CSS中的属性值和单位很重要,因为它们决定了网页上元素的大小、比例和位置。

单位,定义用于指定值的测量系统。CSS提供了许多不同的单位来表示长度和测量。CSS单元用于指定页面元素或其内容的属性值大小。

在CSS中指定和测量长度的方法有很多。它用于指定页边距、填充、字体大小、宽度、高度、边框等。

例如字体大小:50px,这里数字50有一个后缀px,即像素,它是一个CSS测量单位。

数字和单位之间不应该有空格。当值为0时,该单位可以省略。

下表显示了CSS样式中主要使用的不同类型的值和单位:

数据类型描述例子
<integer>表示整数55、-55 等
<number>表示十进制数,可能有小数点1.5、234、-1.5 等
<dimension>表示带有单位的 <number>,也包括像 lengthangletimeresolution 等值类型5px、30deg、2s、2.5dpi 等
<percentage>表示其他值的百分比,即始终相对于其他值80%、25% 等

长度单位可以分为两种类型:

  • 绝对单位
  • 相对单位

绝对长度单位

这些单位被归类为固定长度单位,这意味着用绝对单位指定的长度在屏幕上保持精确、不变的大小。

当浏览器拥有有关屏幕属性、正在使用的打印机或其他适当的用户代理的全面信息时,这些单位非常有效。

下表包含所有类型的绝对单位:

单位描述等价值示例
mm毫米,用于指定毫米单位的测量1mm = 1/10th of 1cmfont-size: 10mm;
cm厘米,用于指定厘米单位的测量1cm = 37.8px = 25.2/64infont-size: 5cm;
Q四分之一毫米,用于指定厘米单位的测量1Q = 1/40th of 1cmfont-size: 5Q;
in英寸,用于指定英寸单位的测量1in = 2.54cm = 96pxfont-size: 1in;
pt磅,用于指定磅单位的测量1pt = 1/72 of 1infont-size: 20pt;
pcPicas,用于指定Picas单位的测量1pc = 1/6th of 1inwidth: 6pc;
px像素,用于指定像素单位的测量1px = 1/96th of 1infont-size: 15px;

事实证明,绝对单位对响应性不是优先事项的项目很有价值。然而,它们对响应式网站不太有利,因为它们在屏幕尺寸变化时不会调整。

使用mm,cm,in,Q单位

以下是绝对单位(mm,cm,in,Q)的示例:

<html>
<head>
<style>
   .unit-mm {
      font-size: 5mm;
   }
   .unit-cm {
      font-size: 1cm;
   }
   .unit-inch {
      font-size: 0.5in;
   }
   .unit-quarter {
      font-size: 40Q;
   }
</style>
</head>
<body>
   <h1 class=”unit-mm“>Font size 5mm</h1>
   <h1 class=”unit-cm“>Font size 1cm</h1>
   <h1 class=”unit-inch“>Font size 0.5inch</h1>
   <h1 class=”unit-quarter“>Font size 40Q</h1>
</body>
</html>

使用px,pt,pc单位

以下是绝对单位(px、pt、pc)的示例:

<html>
<head>
<style>
   .unit-px {
      font-size: 20px;
   }
   .unit-pt {
      font-size: 25pt;
   }
   .unit-pc {
      font-size: 3pc;
   }
</style>
</head>
<body>
   <h1 class=”unit-px“>Font size 20px</h1>
   <h1 class=”unit-pt“>Font size 25pt</h1>
   <h1 class=”unit-pc“>Font size 3pc</h1>
</body>
</html>