CSS Pseudo-classes là biểu diễn các trạng thái đặc biệt của các phần tử khác nhau. Các class này không chỉ mô tả các phần tử cơ bản trong tài liệu mà còn các yếu tố bên ngoài như trạng thái, vị trí, lịch sử, v.v. Sử dụng các pseudo-classes này, nhà phát triển thậm chí có thể định dạng các phần tử không thể chọn trực tiếp qua CSS selectors.
Cú pháp
Selector:pseudo-class {
css-property: /*value*/;
}
Ví dụ 1: :valid và :invalid cho form validation
<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo Class</title>
<style>
form { width: 70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin: 5px; }
input:valid { color: #fefefe; background-color: #4CAF50; }
input:invalid { color: #fefefe; background-color: #DC3545; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Pseudo Class</legend>
<label for="EmailSelect">Email : <input type="email" id="EmailSelect" size="25" required> </label><br>
<label for="PassSelect">Password : <input type="password" id="PassSelect" minlength="8" required> </label>
<div id="divDisplay">Min. Strength of Password: 8<br>Both Fields are Required</div>
</fieldset>
</form>
</body>
</html>
Kết quả
Khi các trường form có dữ liệu không hợp lệ:

Khi các trường form có dữ liệu hợp lệ:

Ví dụ 2: :target để highlight phần tử được liên kết
<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo Class</title>
<style>
form { width: 70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin: 5px; }
a { text-decoration: none; background: grey; color: white; border-radius: 3px; padding: 6px; }
input[type="button"] { border-radius: 10px; }
:target { border: 4px solid black; margin: 0 auto; height: 200px; width: 200px; background-image: url('https://www.tutorialspoint.com/arangodb/images/arangodb-mini-logo.jpg'); }
#circle { border-radius: 50%; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Pseudo Class</legend>
<div>
<div id="circle"></div>
<div id="square"></div>
</div>
<div>
<a href="#square">Tile</a>
<a href="#circle">Avatar</a>
</div>
</fieldset>
</form>
</body>
</html>
Kết quả
Trước khi nhấn nút nào:

Sau khi nhấn nút 'Tile':

Sau khi nhấn nút 'Avatar':

Phân loại Pseudo-classes:
- Trạng thái UI: :hover, :active, :focus, :enabled, :disabled, :checked
- Cấu trúc: :first-child, :last-child, :nth-child(), :nth-of-type(), :only-child
- Form validation: :valid, :invalid, :in-range, :out-of-range, :required, :optional
- Liên kết: :link, :visited, :target
- Ngôn ngữ: :lang()
- Khác: :root, :empty, :not()