Skip to content


Overview of CSS3 structural pseudo-classes(1) – the ‘:target ‘ pseudo-class

E:target

Selects the element E referenced by the fragment identifier (if any) of the page’s URL. this lets you dynamically select the jumped-to anchor from an HTML anchor on the page.

target 伪类可以动态选择页面中具有锚点的元素。


通常一个页面都是有一个URL地址,但是如果这个地址如果是以#something 结尾 链接到特定的元素的话,浏览器会尝试着确定这个元素是否存在(可见)或者是否是在页面的顶端。

:target 伪类可以选择这个特定的元素。

当然可以做的更多,比如,你可以判断这个元素是否选中来隐藏或者显示这个元素。

一个简单的例子:

<a href="#item1">item 1</a>
<a href="#item2">item 2</a>
<a href="#item3">item 3</a>
<a href="#default">clear</a>
<div class="items">
<p id="item1">... item 1...</p>
<p id="item2">... item 2...</p>
<p id="item3">...item 3...</p>
<p id="default">no target</p>

</div>

相应的css,

div.items p {display: none}
div.items p:target {display: block}

非常简单的一个选项卡切换功能,只用了css3就实现。

你可以另外加些样式,使之看起来更像一个按钮。

实际上,在那些支持css3的浏览器你可以用’:not(:target)’隐藏没有被选择的元素。相应代码:

div.items p:not(:target) {display: none}
div.items p:target {display: block}

Posted in 前端开发. Tagged with , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

You must be logged in to post a comment.