Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

CSS font-size với Keywords: Từ khóa tuyệt đối và tương đối

Thuộc tính CSS font-size có thể được thiết lập bằng từ khóa tuyệt đối (absolute) và tương đối (relative). Điều này scale văn bản như mong muốn.

Cú pháp

selector {
    font-size: /* keyword */;
}

Từ khóa tuyệt đối (Absolute-size keywords)

STTKeywordMô tảTỷ lệ so với medium
1xx-smallRất rất nhỏ~3/5 (0.6x)
2x-smallRất nhỏ~3/4 (0.75x)
3smallNhỏ~8/9 (0.89x)
4mediumTrung bình (mặc định)1x (baseline)
5largeLớn~6/5 (1.2x)
6x-largeRất lớn~3/2 (1.5x)
7xx-largeRất rất lớn~2/1 (2x)
8xxx-largeCực lớn (CSS Fonts 4)~3x

Từ khóa tương đối (Relative-size keywords)

KeywordMô tả
smallerNhỏ hơn parent một bậc
largerLớn hơn parent một bậc

Ví dụ 1: larger, medium, xx-large

<!DOCTYPE html>
<html>
<head>
<style>
h1 { font-size: larger; }
#demo { font-size: medium; text-align: center; background-color: floralwhite; }
p { font-size: xx-large; }
</style>
</head>
<body>
<h1>Demo Heading</h1>
<p id="demo">This is demo text.</p>
<p>This is another demo text.</p>
</body>
</html>

Ví dụ 2: xx-small container + xx-large child

<!DOCTYPE html>
<html>
<head>
<style>
div {
    margin: auto; padding: 5px; width: 30%;
    border: 1px solid; border-radius: 29%;
    text-align: center; font-size: xx-small;
}
p { font-size: xx-large; }
</style>
</head>
<body>
<div>
    <div>One</div>
    <p>Two</p>
</div>
</body>
</html>

Keyword vs Unit (px, em, rem)

Đặc điểmKeywordUnit (rem/em)
Respect user setting✅ Có (medium = browser default)❌ rem/em cố định nếu root fixed
Precision7-8 bậc cố định✅ Bất kỳ giá trị nào
ScalingTỷ lệ trình duyệt định sẵnTự kiểm soát
Use caseQuick prototype, respect accessibilityDesign system, precise control

Kết hợp keyword với relative

html { font-size: medium; } /* Baseline = user preference */
body { font-size: 1rem; }   /* 1rem = medium */
h1 { font-size: xx-large; } /* Keyword scale từ medium */
h2 { font-size: x-large; }
.small { font-size: smaller; } /* Relative to parent */

Modern: clamp() cho fluid typography

h1 { font-size: clamp(x-large, 5vw + 1rem, xx-large); }
p { font-size: clamp(small, 1.5vw + 0.5rem, medium); }

Kết hợp keyword làm min/max trong clamp() cho responsive tự nhiên.