Bộ chọn nhóm (grouping selector) trong CSS được dùng để chọn nhiều phần tử và style chúng cùng lúc. Điều này giảm thiểu code và nỗ lực khai báo style chung cho từng phần tử. Để nhóm selector, mỗi selector được phân cách bằng dấu phẩy comma (,).
Cú pháp
element, element {
/* declarations */
}
Ví dụ 1: Group article, p, img
<!DOCTYPE html>
<html>
<head>
<style>
article, p, img {
display: block;
margin: auto;
text-align: center;
border-bottom: double orange;
}
</style>
</head>
<body>
<article>Demo Text</article>
<p>This is demo text.</p>
<br/>
<img src="swing.jpg">
</body>
</html>
Ví dụ 2: Group pseudo-elements
<!DOCTYPE html>
<html>
<head>
<style>
div::after, p::after {
content: "Demo text";
margin: 4px;
box-shadow: inset 0 0 4px darkorange;
}
</style>
</head>
<body>
<div></div>
<p>This is example text.</p>
</body>
</html>
Các loại Grouping
| Loại | Ví dụ | Mô tả |
|---|---|---|
| Element | h1, h2, h3 | Tất cả heading |
| Class | .btn, .button | Nhiều class chung style |
| ID | #header, #footer | Ít dùng (ID unique) |
| Attribute | [type="text"], [type="email"] | Input types |
| Pseudo-class | :hover, :focus | Interactive states |
| Pseudo-element | ::before, ::after | Generated content |
| Kết hợp | .card, article, .post | Component + semantic |
Specificity trong Grouping
Mỗi selector trong group được tính specificity riêng biệt. Rule áp dụng cho element nào thì specificity của selector khớp element đó được dùng.
/* Specificity: (0,1,0) cho .btn, (0,0,1) cho button */
.btn, button { padding: 0.5rem 1rem; }
/* Nếu button có class .btn → specificity (0,1,1) */
Best Practice
- Gom các selector chia sẻ cùng một tập declaration
- Tránh group quá nhiều selector không liên quan — khó bảo trì
- Dùng comment phân nhóm trong file CSS lớn
- Cân nhắc dùng CSS custom properties thay vì group selector cho giá trị lặp lại
/ * Thay vì group selector cho color */
.btn, .link, .badge { color: #0066cc; }
/ * Dùng custom property */
:root { --brand-color: #0066cc; }
.btn, .link, .badge { color: var(--brand-color); }