`target selector` dùng để biểu diễn một phần tử duy nhất với ID khớp với fragment URL. Nó có thể được dùng để tạo kiểu cho phần tử đích hiện tại. URL có dấu # theo sau là tên neo liên kết đến một phần tử cụ thể trong tài liệu. Phần tử được liên kết đến chính là phần tử đích.
Syntax:
:target {
// CSS Property
}
Example 1: Trong ví dụ này, `:target selector` áp dụng các kiểu CSS cho phần tử đích. Phần tử này được chỉ định trong URL fragment, cho phép tùy chỉnh.
HTML<!DOCTYPE html>
<html>
<head>
<title>CSS | :target Selector</title>
<style>
/* CSS property of target selector */
:target {
border: 2px solid #D4D4D4;
background-color: green;
color: white;
padding: 10px;
font-size: 20px;
}
</style>
</head>
<body style="text-align:center">
<h2>
:target selector
</h2>
<p>
<a href="#geek">
Jump to Algorithms
</a>
</p>
<p id="geek">
<b>Algorithms</b>
</p>
</body>
</html>
Output:
Example 2: Trong ví dụ này, `:target selector` được dùng để tạo kiểu cho phần tử đích. Việc tạo kiểu dựa trên URL fragment, hiển thị nội dung một cách linh động.
HTML<!DOCTYPE html>
<html>
<head>
<title>:target Selector</title>
<style>
.tab div {
display: none;
}
.tab div:target {
display: block;
color: white;
background: green;
padding: 5px;
margin: 20px 5px;
}
</style>
</head>
<body style="text-align:center">
<h2>
:target selector
</h2>
<div class="tab">
<a href="#geek">Geeks Classes</a>
<div id="geek">
<h3>Welcome to Geeks Classes.</h3>
<p>Hello World!</p>
</div>
</div>
</body>
</html>
Output:
Supported Browsers: Các trình duyệt được hỗ trợ bởi :target Selector được liệt kê dưới đây:
- Apple Safari 1.3
- Google Chrome 1.0
- Edge 12.0
- Firefox 1.0
- Opera 9.5