纯CSS3运用:target伪类元素做tab切换

朋友提起的: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.效果图

这个属性还能实现更多想要的效果。下次再分享其他的。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值