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

CSS font-size với đơn vị em

Để có kích thước văn bản có thể scale (tỷ lệ), font-size được biểu diễn bằng em. Mặc định 1em = 16px hoặc 12pt. Giá trị của nó tương đối với font-size của phần tử cha.

Cú pháp

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

Cơ chế em

  • 1em = font-size của phần tử cha
  • Lồng nhau: con nhân với cha (compounding)
  • Ví dụ: parent 16px → child 1.5em = 24px → grandchild 1.5em = 36px

Ví dụ 1: Div 1em + Span 2em

<!DOCTYPE html>
<html>
<head>
<style>
div {
    width: 40%; border: 2px solid yellow;
    padding: 20px; font-size: 1em; /* 16px mặc định */
}
span { font-size: 2em; background-color: chartreuse; } /* 32px */
</style>
</head>
<body>
<div>
    <p>This is a demo paragraph<span> displaying font sizes</span> set with em in CSS.</p>
</div>
</body>
</html>

Ví dụ 2: Table 0.8em + Span 1.5em

<!DOCTYPE html>
<html>
<head>
<style>
table { width: 40%; border: 2px ridge red; font-size: 0.8em; } /* 12.8px */
span { font-size: 1.5em; background-color: silver; } /* 19.2px (0.8 * 1.5 * 16) */
</style>
</head>
<body>
<h2>Class Info</h2>
<table>
    <tr><th>Number of Students</th></tr>
    <tr><td>Class A</td><td><span>50 Students</span></td></tr>
    <tr><td>Class B</td><td><span>40 Students</span></td></tr>
</table>
</body>
</html>

em vs rem - So sánh

Đặc điểmemrem
Tương đối vớiParent elementRoot (html)
CompoundingCó (nhân chồng)Không
Dùng choComponent internal scalingGlobal sizing, layout
PredictabilityKhó đoán trước nếu lồng sâu

Khi nào dùng em?

  • Component tự chứa: button, card, modal — scale theo context
  • Icon size theo font: svg { width: 1em; height: 1em; }
  • Spacing nội bộ: padding: 0.5em 1em; scale cùng text
  • Media query: @media (min-width: 30em) — dựa trên font-size root

Tránh compounding không mong muốn

/ * Sử dụng rem cho font-size, em cho spacing trong component */
.card {
    font-size: 1rem;        /* Fixed, không compound */
    padding: 1em 1.5em;     /* Scale với font-size của card */
}
.card-title { font-size: 1.25em; } /* 1.25rem */
.card-text { font-size: 1em; }     /* 1rem */