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

Hướng dẫn thực tế Font Styling (Định dạng phông chữ) với CSS

CSS đóng vai trò then chốt trong việc định dạng phông chữ. Các thuộc tính font CSS cho phép thay đổi font-family, font-size, font-weight, font-kerning, và nhiều thuộc tính hơn nữa. Thuộc tính shorthand font gộp: font-style, font-variant, font-weight, font-size/line-height và font-family. Bên cạnh đó, ta có thể áp dụng style cho văn bản thông qua text-decoration dùng CSS text-shadow, text-stroke, text-fill-color, color, v.v.

Các thuộc tính chính cho văn bản

  • color - Thay đổi màu văn bản
  • font-family - Đặt mặt phông chữ
  • font-kerning - Khoảng cách ký tự đều đặn
  • font-size - Kích thước phông chữ
  • font-stretch - Mặt phông chữ condensed/expanded
  • font-style - In nghiêng (normal, italic, oblique)
  • font-variant - Small-caps (chữ hoa nhỏ)
  • font-weight - Độ đậm (normal, bold, 100-900)
  • line-height - Khoảng cách giữa hai dòng
  • text-decoration - Gạch chân, gạch trên, style
  • text-shadow - Đổ bóng cho ký tự (giống box-shadow)

Ngoài ra có các thuộc tính layout văn bản: text-indent, text-overflow, white-space, word-break, direction, hyphens, text-orientation, word-wrap, v.v.

Cú pháp

Selector {
  font-property: /*value*/
}

Ví dụ 1: Font shorthand và text-shadow

<!DOCTYPE html>
<html>
<head>
<style>
  p { font: 1.6em arial; text-shadow: -3px -12px lightblue; }
  p + p { font: italic bold 12px/30px menu; text-shadow: unset; box-shadow: 0 0 5px 1px black; }
  div { width: 30%; font-size: 1.4em; font-family: cursive; background-color: tomato; }
</style>
</head>
<body>
  <h2>Demo Heading</h2>
  <p>This is demo text</p>
  <p>This text is for demo and included here to display different font styles in CSS.</p>
  <div>Another text with different font style.</div>
</body>
</html>

Kết quả

Hướng dẫn thực tế Font Styling (Định dạng phông chữ) với CSS

Ví dụ 2: Font shorthand phức tạp

<!DOCTYPE html>
<html>
<head>
<style>
  p { font: oblique 5deg small-caps bold 1.3em/0.5px cursive; border: 3px solid lightcyan; }
</style>
</head>
<body>
  <p>This is demo text</p>
  <p>This is another demo text</p>
</body>
</html>

Kết quả

Hướng dẫn thực tế Font Styling (Định dạng phông chữ) với CSS

Mẹo font shorthand:

  • Bắt buộc có font-size và font-family
  • Thứ tự: style variant weight size/line-height family
  • line-height tách bằng dấu / sau font-size
  • Giá trị bỏ qua sẽ lấy mặc định

Text-shadow syntax: text-shadow: h-offset v-offset blur-radius color; - có thể thêm nhiều shadow cách nhau bởi dấu phẩy.