Thuộc tính CSS font-weight được dùng để định nghĩa độ đậm (boldness) của các ký tự văn bản của một phần tử.
Cú pháp
selector {
font-weight: normal | bold | bolder | lighter | 100-900;
}
Các giá trị
| Giá trị | Tên | Trọng số |
|---|---|---|
100 | Thin | 100 |
200 | Extra Light | 200 |
300 | Light | 300 |
400 | Normal / Regular | 400 (mặc định) |
500 | Medium | 500 |
600 | Semi Bold | 600 |
700 | Bold | 700 |
800 | Extra Bold | 800 |
900 | Black / Heavy | 900 |
normal | = 400 | |
bold | = 700 | |
bolder | Đậm hơn parent | Tăng một bậc |
lighter | Mỏng hơn parent | Giảm một bậc |
Ví dụ 1: Các mức độ đậm
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 3px; font-family: "Ink Free";
width: 30%; font-size: 24px;
}
#one { font-weight: normal; border-bottom: 2px dashed greenyellow; }
#two { font-family: "Kristen ITC"; font-weight: bolder; border-bottom: 2px dashed cornflowerblue; }
#three { font-weight: bold; border-bottom: 2px dashed chocolate; }
</style>
</head>
<body>
<div id="one">First Demo Text</div>
<div id="two">Another Demo Text</div>
<div id="three">Last Demo Text</div>
</body>
</html>
Ví dụ 2: Attribute selector kết hợp font-weight
<!DOCTYPE html>
<html>
<head>
<style>
[class|="lis"] { font-style: italic; font-weight: bold; }
li[class|="lis-ul"] {
background-color: cadetblue;
font-family: Helvetica;
font-weight: 100;
color: gainsboro;
width: 20%;
}
</style>
</head>
<body>
<h2>Tutorials</h2>
<ol>
<li><p>C#</li>
<li class="lis-ul-2">DBMS</li>
<li class="lis-3">OS</li>
<li>Java</li>
<ul>
<li class="lis-ul-one">Core Java</li>
<li class="lis">Advance Java</li>
</ul>
</ol>
</body>
</html>
Lưu ý quan trọng
- Font phải hỗ trợ các trọng số tương ứng (variable font hoặc nhiều file font)
- Nếu font không có weight 300, trình duyệt sẽ map sang weight gần nhất có sẵn
bolder/lightertính tương đối so với parent — hữu ích cho nested emphasis- System fonts (system-ui) thường có đầy đủ weight 400/500/600/700
Best Practice: Variable Fonts
@font-face {
font-family: 'Inter';
src: url('Inter-Variable.woff2') format('woff2-variations');
font-weight: 100 900; /* Tất cả weight trong 1 file */
}
body { font-family: 'Inter', system-ui, sans-serif; }
h1 { font-weight: 700; }
h2 { font-weight: 600; }
.body { font-weight: 400; }
.caption { font-weight: 300; }
Variable font giảm kích thước file và cho phép mọi giá trị weight (100-900).