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

Thiết lập cỡ chữ (Font Size) bằng từ khóa trong CSS

Để thiết lập cỡ chữ với thuộc tính font-size, bạn có thể dùng từ khóa. Chúng chia thành 2 loại:

Từ khóa kích thước tương đối (Relative-size keywords)

  • larger: Lớn hơn cỡ chữ cha
  • smaller: Nhỏ hơn cỡ chữ cha

Từ khóa kích thước tuyệt đối (Absolute-size keywords)

  • xx-small, x-small, small, medium (mặc định)
  • large, x-large, xx-large, xxx-large

Ví dụ 1: Từ khóa tuyệt đối

<!DOCTYPE html>
<html>
<head>
<style>
.demo { grid-area: newArea; font-size: xx-large; }
.item3 { font-size: small; }
.item4 { font-size: medium; }
.item5 { font-size: x-large; }
.grid-container {
  display: grid;
  grid-template-areas: 
    'newArea newArea . . .'
    'newArea newArea . . .';
  grid-gap: 5px;
  background-color: blue;
  padding: 5px;
}
.grid-container > div {
  background-color: orange;
  text-align: center;
  padding: 5px 0;
}
</style>
</head>
<body>
<h1>Tiêu đề Một</h1>
<p>Đặt một số số ngẫu nhiên</p>
<div class="grid-container">
  <div class="demo">250</div>
  <div class="item2">120</div>
  <div class="item3">333</div>
  <div class="item4">298</div>
  <div class="item5">645</div>
  <div class="item6">543</div>
  <div class="item7">555</div>
</div>
</body>
</html>

Kết quả

Thiết lập cỡ chữ (Font Size) bằng từ khóa trong CSS

Ví dụ 2: Từ khóa tương đối

<!DOCTYPE html>
<html>
<head>
<style>
.demo { grid-area: newArea; font-size: smaller; }
.item3 { font-size: smaller; }
.item4 { font-size: larger; }
.item5 { font-size: larger; }
.grid-container {
  display: grid;
  grid-template-areas: 
    'newArea newArea . . .'
    'newArea newArea . . .';
  grid-gap: 5px;
  background-color: blue;
  padding: 5px;
}
.grid-container > div {
  background-color: orange;
  text-align: center;
  padding: 5px 0;
}
</style>
</head>
<body>
<h1>Tiêu đề Một</h1>
<p>Đặt một số số ngẫu nhiên</p>
<div class="grid-container">
  <div class="demo">250</div>
  <div class="item2">120</div>
  <div class="item3">333</div>
  <div class="item4">298</div>
  <div class="item5">645</div>
  <div class="item6">543</div>
  <div class="item7">555</div>
</div>
</body>
</html>

Kết quả

Thiết lập cỡ chữ (Font Size) bằng từ khóa trong CSS

Lưu ý:

  • Tuyệt đối: Không phụ thuộc cỡ chữ cha, tỷ lệ cố định giữa các mức
  • Tương đối: Dựa trên cỡ chữ của phần tử cha
  • Phù hợp cho accessibility (người dùng zoom font)
  • Hiện đại hơn: dùng rem cho gốc, em cho tương đối