CSS 單位 (絕對長度和相對長度)
最近在開發響應式網頁的時候,字體大小總是影響效果,原因就是使用了絕對長度單位導致的,因此讓我們一起來了解一下CSS中有哪些單位是絕對長度、相對長度的,在開發中又如何使用呢!
絕對長度
下列這些是固定長度的單位,使用絕對單位表示的長度將顯示為與該大小完全相同。不建議在屏幕上使用,因為屏幕的大小變化太大。因此,當輸出介質已知時,應使用絕對單位,例如打印布局。
當項目中不考慮響應能力時,絕對單位很有用。它們對響應式網站不太有利,因為它們不會在屏幕更改時縮放。
通常,絕對長度始終被視為相同的大小。絕對長度單位的表格如下:
cm | 厘米 |
---|---|
mm | 毫米 |
in | 英寸 (1in = 96px = 2.54cm) |
px * | 像素 (1px = 1/96th of 1in) |
pt | 點 (1pt = 1/72 of 1in) |
pc | 派卡 (1pc = 12 pt) |
***** 像素(px)是相對於觀看設備的。對於低 dpi 的設備,1px 是顯示器的一個設備像素(點)。對於打印機和高分辨率屏幕,1px 表示多個設備像素。
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<h1> Absolute units </h1>
<p style="font-size: 20px;"> It has a font-size: 20px; </p>
<p style="font-size: 1.2cm;"> It has a font-size: 1.2cm; </p>
<p style="font-size: .7in;"> It has a font-size: .7in; </p>
<p style="font-size: 18pt;"> It has a font-size: 18pt; </p>
<p style="font-size: 2pc;"> It has a font-size: 2pc; </p>
<p style="font-size: 10mm;"> It has a font-size: 10mm; </p>
</body>
</html>
相對長度
相對單位非常適合設置響應式網站的樣式,因為它們相對於窗口大小或父級進行縮放。它們指定長度,該長度相對於另一個 length 屬性。
根據設備的不同,如果屏幕的大小變化太大,則相對長度單位是最好的,因為它們在不同的渲染媒體之間可以更好地縮放。我們可以使用相對單位作為響應單位的默認值。它有助於我們避免更新不同屏幕尺寸的樣式。
相對長度單位的表格如下:
單位 | 描述 |
---|---|
em | 相對於元素的字體大小(font-size)(2em 表示當前字體大小的 2 倍) |
ex | 相對於當前字體的 x-height(極少使用) |
ch | 相對於 "0"(零)的寬度 |
rem | 相對於根元素的字體大小(font-size) |
vw | 相對於視口*寬度的 1% |
vh | 相對於視口*高度的 1% |
vmin | 相對於視口*較小尺寸的 1% |
vmax | 相對於視口*較大尺寸的 1% |
% | 用於設置元素的寬度時,它總是相對於其直接父元素的大小。如果沒有定義的父級,則默認情況下 body 會被視為父級。 |
***** 視口(Viewport)= 瀏覽器窗口的尺寸。如果視口為 50 厘米寬,則 1vw = 0.5 厘米。
因此,我們要開發響應式網站,一般常用em、rem兩個單位:
- em總是相對於它的直接父級的字體大小,如父元素字體為10px,則1em=10px,2em=20px;
- rem總是相對於根元素的字體大小,即html元素,而跟父元素的字體大小無關,如根元素字體10px,直接父元素為20px時,1rem=10px,而不是20px;
<!DOCTYPE html>
<html>
<head>
<style>
html {
/* 修改此屬性查看rem的變化 */
font-size: 20px;
}
body {
text-align: center;
/* 修改此屬性查看em的變化 */
font-size: 20px;
}
p {
line-height: 0.1cm;
color: blue;
}
</style>
</head>
<body>
<h1> Relative units </h1>
<p style="font-size: 2em;"> It has a font-size: 2em; </p>
<p style="font-size: 8ex;"> It has a font-size: 8ex; </p>
<p style="font-size: 6ch;"> It has a font-size: 6ch; </p>
<p style="font-size: 4rem;"> It has a font-size: 4rem; </p>
<p style="font-size: 4vw;"> It has a font-size: 4vw; </p>
<p style="font-size: 10vh;"> It has a font-size: 10vh; </p>
<p style="font-size: 10vmin;"> It has a font-size: 10vmin; </p>
<p style="font-size: 8vmax;"> It has a font-size: 8vmax; </p>
<p style="font-size: 400%;"> It has a font-size: 400%; </p>
</body>
</html>
文檔下載
此文章系原創,轉載請附上鏈接,抱拳...
此文檔提供markdown源文件下載,請去我的碼雲倉庫進行下載... 下載文檔
若本文對你有用,請不要忘記給我的點個Star哦....