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

Pseudo-element CSS ::before - Chèn nội dung trước phần tử


Pseudo-element ::before trong CSS

Pseudo-element ::before cho phép **chèn nội dung trước nội dung của phần tử** mà không sửa HTML. Dùng chung với thuộc tính content. Đối xứng với ::after.

Cú pháp

selector::before {
  content: "nội dung";  /* Bắt buộc - có thể là chuỗi rỗng "" */
  /* Style khác: display, color, margin, position... */
}

Các giá trị content (giống ::after)

Loại Ví dụ Mô tả
Văn bản content: "★ "; Thêm ký tự/trước text
Hình ảnh content: url("icon.png"); Chèn ảnh (không resize được)
Counter content: counter(item) ". "; Số thứ tự tự động
Attribute content: attr(data-label); Lấy giá trị attribute
Rỗng content: ""; Tạo element cho styling

Ví dụ cơ bản (từ bài gốc)

<!DOCTYPE html>
<html>
<head>
  <style>
    p::before {
      content: url(/images/bullet.gif);
      margin-right: 8px;
    }
  </style>
</head>
<body>
  <p>Dòng này sẽ có bullet ở đầu.</p>
  <p>Dòng này cũng sẽ có bullet ở đầu.</p>
  <p>Dòng này nữa.</p>
</body>
</html>

Ví dụ nâng cao thực tế

1. Custom list marker (thay bullet mặc định)

ul.custom-list { list-style: none; padding-left: 0; }
ul.custom-list li { position: relative; padding-left: 1.5em; }
ul.custom-list li::before {
  content: "▸";
  position: absolute; left: 0;
  color: #667eea;
  font-weight: bold;
}

2. Quote marks cho blockquote

blockquote::before {
  content: open-quote;  /* " hoặc « tùy locale */
  font-size: 3em; color: #ccc;
  position: absolute; top: -0.5em; left: -0.2em;
}
blockquote::after {
  content: close-quote;
  font-size: 3em; color: #ccc;
}

3. Badge/Label cho element

.new-badge::before {
  content: "NEW";
  position: absolute; top: -8px; right: -8px;
  background: #FF5722; color: white;
  font-size: 0.6em; font-weight: bold;
  padding: 2px 6px; border-radius: 10px;
  white-space: nowrap;
}

4. Clearfix (cũ, giờ dùng flow-root)

.clearfix::before,
.clearfix::after {
  content: "";
  display: table;
}
.clearfix::after { clear: both; }

5. Decorative line/underline

.section-title::before {
  content: "";
  display: block;
  width: 60px; height: 3px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  margin-bottom: 8px;
}

Lưu ý quan trọng

  • Tạo pseudo-element **con** của element - không trong DOM
  • Mặc định display: inline - thường cần đổi block/inline-block/absolute
  • Kế thừa thuộc tính inheritable từ parent (color, font...)
  • CSS2: :before (1 dấu), CSS3: ::before (2 dấu) - nên dùng 2 dấu
  • Không thể truy cập bằng JavaScript (querySelector không thấy)