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哦....
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373889.html
標籤:Html/Css
