朋友提起的:target这个css属性,先去W3C查看了一下兼容,下面是官方的定义和用法。
自己用这个属性做了一个纯CSS的tab切换效果,发现还不错。(不过这个适合数量很少并且固定个数的tab切换,为了方便遍历的话,建议还是使用JS。)
1.thml代码
<div class="container">
<div id="content1" class="active">生活</div>
<div id="content2">美食</div>
<div id="content3">娱乐</div>
<div id="content4">其他</div>
<ul class='nav'>
<li class="active"><a href="#content1">生活</a></li>
<li><a href="#content2">美食</a></li>
<li><a href="#content3">娱乐</a></li>
<li><a href="#content4">其他</a></li>
</ul>
</div>
2.CSS代码
html,body{
width: 100%;
float: left;
margin: 0;
padding: 0;
}
ul,li{
margin: 0;
padding: 0;
list-style: none;
}
.container {
width: 100%;
margin: 0;
padding: 0;
}
li {
width: 25%;
float: left;
text-align: center;
background: #ddd;
}
li a {
display: block;
width: 100%;
line-height: 36px;
font-size: 18px;
cursor: pointer;
text-decoration: none;
color: #000;
}
#content1,
#content2,
#content3,
#content4 {
position: absolute;
overflow: hidden;
top: 36px;
width: 400px;
height: 100px;
border: 1px solid #999;
box-sizing: border-box;
padding: 10px;
}
#content1,
#content2,
#content3,
#content4 {
display: none;
width: 100%;
background: #fff;
}
#content1:target,
#content2:target,
#content3:target,
#content4:target {
display: block;
}
#content1.active {
display: block;
}
.active ~ .nav li:first-child {
background: #ff7300;
color: #fff;
}
#content1:target ~ .nav li{
background: #ddd;
color: #000;
}
#content1:target ~ .nav li:first-child {
background: #ff7300;
color: #fff;
}
#content2:target ~ .nav li {
background: #ddd;
color: #000;
}
#content2:target ~ .nav li:nth-child(2) {
background: #ff7300;
color: #fff;
}
#content3:target ~ .nav li {
background: #ddd;
color: #000;
}
#content3:target ~ .nav li:nth-child(3) {
background: #ff7300;
color: #fff;
}
#content4:target ~ .nav li {
background: #ddd;
color: #000;
}
#content4:target ~ .nav li:last-child {
background: #ff7300;
color: #fff;
}
3.效果图
这个属性还能实现更多想要的效果。下次再分享其他的。