理解 CSS 绝对单位和相对单位
网页上的字体、高度、宽度、边距、填充等都通过长度单位来设置。例如,高度 100px,宽度 100px,字体 2em 等。这些长度单位分为绝对单位和相对单位。
CSS 绝对单位
绝对长度单位彼此之间是固定的。当输出格式已知时,使用这些单位。以下是其中一些绝对长度单位:
序号 |
单位及描述 |
|---|---|
1 |
cm 厘米 |
2 |
mm 毫米 |
3 |
in 英寸 (1in = 96px = 2.54cm) |
4 |
px * 像素 (1px = 1/96 英寸) |
5 |
pt 磅 (1pt = 1/72 英寸) |
6 |
pc 派卡 (1pc = 12 pt) |
绝对单位英寸
现在让我们看一个使用绝对长度单位英寸 (in) 的示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
text-decoration: overline underline;
text-decoration-color: blue;
font-size: 0.3in;
}
</style>
</head>
<body>
<h1>Details</h1>
<p class="demo">Examination Center near ABC College.</p>
<p class="demo2">Exam begins at 9AM.</p>
</body>
</html>
绝对单位像素
让我们再看一个容器高度和宽度使用绝对长度单位像素 (px) 设置的示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin-top: 10px;
height: 200px;
width: 200px;
overflow: auto;
margin: 20px;
}
</style>
</head>
<body>
<h1>Demo Heading</h1>
<div>
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
</div>
</body>
</html>
绝对单位磅
现在让我们看一个使用绝对长度单位磅 (pt) 的示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
p.demo {
border: 2px solid blue;
padding: 35px 70px 50px 40px;
font-size: 20pt;
}
</style>
</head>
<body>
<h1>Demo Heading</h1>
<p>This is a demo text.</p>
<p class="demo">This is another demo text.</p>
<p>Another demo text</p>
<h2>Demo Heading2</h2>
<p>Demo text</p>
</body>
</html>
CSS 相对单位
CSS 中的相对长度单位用于指定相对于其他长度属性的长度。
相对于当前字体的 x 高度
序号 |
单位及描述 |
|---|---|
1 |
em 相对于元素的字体大小,即 4em 表示当前字体大小的 4 倍。 |
2 |
ex 相对于当前字体的 x 高度 |
3 |
ch 相对于 0 的宽度 |
4 |
rem 相对于根元素的字体大小 |
5 |
vw 相对于视口宽度的 1% |
6 |
vh 相对于视口高度的 1% |
7 |
vmin 相对于视口较小尺寸的 1% |
8 |
vmax 相对于视口较大尺寸的 1% |
9 |
% 相对于父元素 |
相对单位 em
让我们看一个使用相对长度单位 em 的示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
text-decoration: overline underline;
text-decoration-color: blue;
font-size: 1.4em;
}
</style>
</head>
<body>
<h1>Details</h1>
<p class="demo">Examination Center near ABC College.</p>
<p class="demo2">Exam begins at 9AM.</p>
</body>
</html>
相对单位 vw
让我们再看一个使用 vw 绝对单位设置字体的示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
font-size: 10vw;
}
p {
font-size: 5vw;
}
</style>
</head>
<body>
<h1>Responsive Text Example</h1>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum, rerum.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Excepturi, necessitatibus officiis hic est in nobis!
</p>
</body>
</html>
相对单位 ch
让我们再看一个使用 ch 绝对单位设置字体的示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
p.demo {
border: 2px solid blue;
padding: 35px 70px 50px 40px;
font-size: 2ch;
}
</style>
</head>
<body>
<h1>Demo Heading</h1>
<p>This is a demo text.</p>
<p class="demo">This is another demo text.</p>
<p>Another demo text</p>
<h2>Demo Heading2</h2>
<p>Demo text</p>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP