:target伪类制作tab选项卡

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

HTML代码:

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

CSS代码:

1 :target{
2    color: #343434;
3    border: 1px solid red;
4    background-color: red;
5 }

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

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

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

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

 代码示例:

 HTML代码:

1 <ul class="tab-title">
2     <li><a href="#music">音乐</a></li>
3     <li><a href="#fun">娱乐</a></li>
4     <li><a href="#photo">摄影</a></li>
5 </ul>
6 <div id="music">音乐</div>
7 <div id="fun">娱乐</div>
8 <div id="photo">摄影</div>

 CSS代码:

 1 ul{
 2   width: 303px;
 3   height: 40px;
 4   text-align: center;
 5   line-height: 40px;
 6   list-style: none;
 7   border: 1px solid #333;
 8   margin: 40px auto 0;
 9   border-top-left-radius: 10px;
10   border-top-right-radius: 10px;
11 }
12 li{
13   float: left;
14   width: 100px;
15   border-right: 1px solid #333;
16   display: table;
17 }
18 li:nth-child(3){
19    border: none;
20 }
21 li > a {
22   color: #333;
23   text-decoration: none;
24   display: table-cell;
25   vertical-align: middle;
26 }
27 li:nth-child(1) > a{
28   border-top-left-radius: 10px;
29 }
30 li:nth-child(3) > a{
31   border-top-right-radius: 10px;
32 }
33 li > a:hover    {
34   background-color: #8BB7F9;
35 }
36 div{
37   position: absolute;      必须
38   left: 161px;
39   width: 303px;
40   height: 150px;
41   line-height: 150px;
42   text-align: center;
43   border: 1px solid #333;
44   border-top: none;
45   border-bottom-left-radius: 10px;
46   border-bottom-right-radius: 10px;
47   background: #fff;
48 }
49 #music:target,#fun:target,#photo:target{
50   z-index: 1;                                                     //必须
51 };

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

 显示效果为:

 

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

  by新手小白的记录

原文地址:https://www.cnblogs.com/lynnmn/p/6219684.html