Pseudo-elements trong CSS không chỉ áp dụng cho các phần tử HTML mà còn có thể áp dụng cho các CSS classes.
Ví dụ: Kết hợp Pseudo-elements với CSS Classes
<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo Elements and CSS Classes</title>
<style>
form {
width: 70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin: 5px;
box-sizing: border-box;
}
input[type="button"] {
border-radius: 10px;
}
.child {
line-height: .1em;
border: 4px solid black;
}
::selection {
color: white;
}
.child:nth-child(1), h1::selection {
background-color: #FF8A00;
}
.child:nth-child(2), div::selection {
background-color: #F44336;
}
.child:nth-child(3), p::selection {
background-color: #C303C3;
}
.child:nth-child(4), article::selection {
background-color: #4CAF50;
}
.child:nth-child(5), code::selection {
background-color: #FEDC11;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Pseudo Elements and CSS Classes</legend>
<div id="container">
<h1>A Heading</h1>
<div>Welcome to DIV World</div>
<p>Every one is welcome in this town. Make yourself comfortable</p>
<article>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</article>
<code>function helloWorld(){ document.write("Hello World");}</code>
<div>
<span class="child">h1</span>
<span class="child">div</span>
<span class="child">p</span>
<span class="child">article</span>
<span class="child">code</span>
</div>
</div>
</fieldset>
</form>
</body></html>
Kết quả
Bố cục ban đầu:

Khi chọn phần tử <h1> và <div>:

Khi chọn phần tử <p> và <article>:

Khi chọn phần tử <code>:

Giải thích: Ví dụ này minh họa cách pseudo-element ::selection (được áp dụng cho các thẻ h1, div, p, article, code) kết hợp với pseudo-class :nth-child() trên class .child để tạo hiệu ứng highlight với màu sắc khác nhau khi người dùng bôi đen văn bản.