Khi ID của element có phần đầu cố định, phần cuối thay đổi (ví dụ: post-1, post-2, post-comment-5), CSS Attribute Selectors cho phép chọn dựa trên pattern.
3 Selector chính
| Selector | Tên | Khớp khi | Ví dụ khớp |
|---|---|---|---|
[id^="prefix"] | Prefix (bắt đầu bằng) | Giá trị attribute bắt đầu bằng "prefix" | post-1, post-abc, post_ |
[id$="suffix"] | Suffix (kết thúc bằng) | Giá trị attribute kết thúc bằng "suffix" | item-post, 123-post, post |
[id*="substring"] | Contains (chứa) | Giá trị attribute chứa "substring" ở bất kỳ vị trí | post-1, my-post-item, post |
Ví dụ thực tế
<div id="post-1" class="post">Bài 1</div> <div id="post-2" class="post">Bài 2</div> <div id="post-comment-3" class="post">Comment</div> <div id="user-post-4" class="post">User post</div> <div id="sidebar">Sidebar</div>
/* Chọn tất cả div có id BẮT ĐẦU bằng "post-" */
div[id^="post-"] {
border-left: 3px solid blue;
}
/* Chọn tất cả div có id KẾT THÚC bằng "-post" */
div[id$="-post"] {
border-right: 3px solid green;
}
/* Chọn tất cả div có id CHỨA "post" ở đâu đó */
div[id*="post"] {
background: #f0f8ff; /* Áp dụng cho cả 4 div đầu */
}
Kết hợp với class/tag
/* Chỉ div.post có id bắt đầu bằng "post-" */
div.post[id^="post-"] { ... }
/* Input có name bắt đầu bằng "user_" */
input[name^="user_"] { ... }
/* Link href kết thúc bằng ".pdf" */
a[href$=".pdf"]::after { content: " (PDF)"; }
Case Sensitivity
- Mặc định: Case-sensitive (phân biệt hoa/thường).
- Case-insensitive: Thêm
itrước ngoặc đóng (hỗ trợ modern browsers):
/* Không phân biệt hoa/thường */
div[id^="post-" i] { ... }
a[href$=".PDF" i] { ... }
Hiệu năng (Performance)
- Attribute selectors chậm hơn class/id selector (browser phải check attribute mọi element).
- Với DOM lớn, ưu tiên thêm class chung (ví dụ
class="post-item") và dùng class selector. - Attribute selector phù hợp cho: dynamic ID, CMS generated content, integration testing.
Ứng dụng thực tế
- Style cho CMS (WordPress:
post-123,comment-456). - Test automation (Cypress, Playwright):
cy.get('[id^="btn-"]'). - Form validation:
input[name$="[]"](mảng). - Icon font:
i[class*="icon-"].