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

CSS font-weight: Độ đậm của chữ

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ênTrọng số
100Thin100
200Extra Light200
300Light300
400Normal / Regular400 (mặc định)
500Medium500
600Semi Bold600
700Bold700
800Extra Bold800
900Black / Heavy900
normal= 400
bold= 700
bolderĐậm hơn parentTăng một bậc
lighterMỏng hơn parentGiả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/lighter tí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).