:target伪类制作tab选项卡

2023-05-10,,

:target伪类的作用是突出显示活动的HTML锚,下面是一个简单的例子:

HTML代码:

 <div>
<a href="#demo1">点击此处</a>
</div>
<div id="demo1">测试结果</div>

CSS代码:

 :target{
color: #343434;
border: 1px solid red;
background-color: red;
}

#demo1写在链接里,表示指向一个目标元素,而id=demo1的div元素即是想要选中的目标元素。这段代码操作后的效果为:

点击a元素之后,目标元素#demo1的样式发生了变化,变化的样式即css代码所写的。

:target是css3新增的属性,目前最常用到的地方便是tab选项卡制作

以前的tab选项卡一般运用js或者jquery来实现,现在只要用css3的:target便可以完成。

代码示例:

HTML代码:

 <ul class="tab-title">
<li><a href="#music">音乐</a></li>
<li><a href="#fun">娱乐</a></li>
<li><a href="#photo">摄影</a></li>
</ul>
<div id="music">音乐</div>
<div id="fun">娱乐</div>
<div id="photo">摄影</div>

CSS代码:

 ul{
width: 303px;
height: 40px;
text-align: center;
line-height: 40px;
list-style: none;
border: 1px solid #333;
margin: 40px auto 0;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
}
li{
float: left;
width: 100px;
border-right: 1px solid #333;
display: table;
}
li:nth-child(3){
border: none;
}
li > a {
color: #333;
text-decoration: none;
display: table-cell;
vertical-align: middle;
}
li:nth-child(1) > a{
border-top-left-radius: 10px;
}
li:nth-child(3) > a{
border-top-right-radius: 10px;
}
li > a:hover {
background-color: #8BB7F9;
}
div{
position: absolute; 必须
left: 161px;
width: 303px;
height: 150px;
line-height: 150px;
text-align: center;
border: 1px solid #333;
border-top: none;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
background: #fff;
}
#music:target,#fun:target,#photo:target{
z-index:; //必须
};

上面代码中除了必须设置:target为index:1,以及目标元素的position:absolute,其他的都是基本样式

显示效果为:

以上就是:target制作tab选项卡的过程

by新手小白的记录

:target伪类制作tab选项卡的相关教程结束。

《:target伪类制作tab选项卡.doc》

下载本文的Word格式文档,以方便收藏与打印。