目标伪类选择器详细说明以及案例
2025-03-11
56
参考资料
目标伪类选择器详细说明以及案例
目标伪类选择器详细说明
目标伪类选择器(:target)用于选择当前活动的目标元素。通常,当用户点击一个指向页面内某个元素的链接时,该元素会成为目标元素,即URL片段标识符(如#section1)所指向的元素。
语法:
:target {
/* 样式规则 */
}特点:
动态匹配:
:target伪类会根据URL中的片段标识符动态匹配元素。唯一性:在同一时间内,只有一个元素可以是目标元素。
应用场景:常用于高亮显示当前活动的锚点内容,或实现简单的页面内导航效果。
浏览器支持:
所有现代浏览器均支持:target伪类。
案例
HTML代码:
<h2 id="section1">Section 1</h2> <p>This is the content of section 1.</p> <h2 id="section2">Section 2</h2> <p>This is the content of section 2.</p> <h2 id="section3">Section 3</h2> <p>This is the content of section 3.</p> <nav> <a href="#section1">Go to Section 1</a> | <a href="#section2">Go to Section 2</a> | <a href="#section3">Go to Section 3</a> </nav>
CSS代码:
:target {
background-color: yellow;
border: 2px solid red;
padding: 10px;
}效果说明:
当用户点击“Go to Section 1”链接时,
#section1元素将应用background-color: yellow;和border: 2px solid red;的样式。同样,点击“Go to Section 2”或“Go to Section 3”链接时,相应的
#section2或#section3元素将应用相同的样式。
总结::target伪类选择器通过动态匹配URL片段标识符,实现对目标元素的样式控制,适用于页面内导航和高亮显示等场景。

