编辑:截至 2020 年,此技术仍然有效并允许链接到选项卡,但如果您要在一页上查找多个选项卡集,请参阅 @chulian 的答案,它使用 input[type=radio] 而不是 :target。
这里有一个现已失效的 html5rockstars.com 演示的存档:
https://web.archive.org/web/20121118201357/http://htmlrockstars.com/blog/using-css-to-create-a-tabbed-content-area-no-js-required/
这里介绍了相同的技术,可以说更好:
http://www.sitepoint.com/css3-tabs-using-target-selector/
归结为您使用 CSS3 :target 选择器来取消隐藏当前选择的任何选项卡。这仅在页面上只有一组选项卡时才有效,但具有完整的浏览器后退按钮支持的优势。例如:
<ul id="menu">
<li><a href="#tab1">First tab</a></li>
<li><a href="#tab2">Second tab</a></li>
<li><a href="#tab3">Third tab</a></li>
</ul>
<div id="tab1" class="tab-content">Content of first tab</div>
<div id="tab2" class="tab-content">Content of second tab</div>
<div id="tab3" class="tab-content">Content of third tab</div>
然后在你的样式表中:
.tab-content {
display: none;
}
.tab-content:target {
display: block;
}
不幸的是,这并不完美,因为在单击其中一个链接之前不会显示任何选项卡内容(除非您链接到 page.html#tab1)。上面的第二个链接建议使用以下内容作为该问题的解决方案:
.tab-content {
z-index: 0;
background-color: white;
position: absolute;
top: 100px;
width: 100%;
height: 300px;
}
.tab-content:first-child {
z-index: 1;
}
.tab-content:target {
z-index: 2;
}
这有点骇人听闻,而且还需要绝对定位。
作为替代方案,如果您不介意将默认选项卡放在 html 中的最后(当然,您可以按自己喜欢的顺序排列链接),您可以这样做:
<ul id="menu">
<li><a href="#tab1">First tab</a></li>
<li><a href="#tab2">Second tab</a></li>
<li><a href="#tab3">Third tab</a></li>
</ul>
<div class="tab-folder">
<div id="tab2" class="tab-content">Content of second tab</div>
<div id="tab3" class="tab-content">Content of third tab</div>
<div id="tab1" class="tab-content">Content of first tab</div>
</div>
CSS:
.tab-folder > .tab-content:target ~ .tab-content:last-child, .tab-folder > .tab-content {
display: none;
}
.tab-folder > :last-child, .tab-folder > .tab-content:target {
display: block;
}
这可以说是最干净的解决方案,也是我会选择的解决方案,除非我怀疑很多人会在关闭 CSS 的情况下访问我的页面。