关于:target伪类在上一篇文章中CSS :target伪类标签切换效果 (无需JS)提到过

下面用:target伪类做了一个图片轮播的效果,主要用到了:~选择器,:target伪类,@ketframes动画。

效果

代码

<div class="box">  

  <div class="img-box">
    <div class="img img1" id="img1"></div>
    <div class="img img2" id="img2"></div>
    <div class="img img3" id="img3"></div>  
  </div>

  <div class="dot">
    <a href="#img1"><span></span></a>
    <a href="#img2"><span></span></a>
    <a href="#img3"><span></span></a>
  </div>

</div>
.box{
  width: 500px;
  height: 270px;
  background: aliceblue;
  position: relative;
}

.img-box{
  width: 100%;
  height: 100%;
  position: relative;
}
.img{
  width: 100%;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  position: absolute;
}
.img1{
  background-image: url(https://wx2.sinaimg.cn/mw690/648ac377gy1ftr11txnsij20yg0oawm2.jpg);
  animation: a 9s linear;
  animation-iteration-count: infinite;
}
.img2{
  background-image: url(https://wx2.sinaimg.cn/mw690/648ac377gy1ftr11u121jj20yg0oaqam.jpg);
  animation: b 9s linear;
  animation-iteration-count: infinite;
}
.img3{
  background-image: url(https://wx2.sinaimg.cn/mw690/648ac377gy1ftr11tu1z3j20zk0p2dlz.jpg);
  animation: c 9s linear;
  animation-iteration-count: infinite;
}

.dot{
  position: absolute;
  bottom: 0;
  right: 7px;
}
.dot span{
  width: 10px;
  height: 10px;
  background: rgba(0,0,0,0.5);
  border: #FFFFFF solid 1px;
  border-radius: 50%;
  z-index: 1;
  margin-left: 5px;
  display: inline-block;
}
.dot span:hover{
  background: #ffffff;
}

#img1:target ~ .img{
  opacity: 0;
}
#img2:target ~ .img{
  opacity: 0;
}
#img3:target{
  opacity: 1;
}

原理

原理与上一篇文章相似,首先使用绝对定位使三张图片重叠,此时显示的会是最后一张

#img1被激活时,使用:target伪类和~选择器,设置第一张图片之后所有的图片opacity: 0即透明,此时第一张照片显示

第二张图片和第三张原理与此相同

图片自动轮播的@keyframes动画代码

@keyframes a{
  0%{opacity: 1;}
  33%{opacity: 0;}
  66%{opacity: 0;}
  100%{opacity: 1;}
}
@keyframes b{
  0%{opacity: 0;}
  33%{opacity: 1;}
  66%{opacity: 0;}
  100%{opacity: 0;}
}
@keyframes c{
  0%{opacity: 0;}
  33%{opacity: 0;}
  66%{opacity: 1;}
  100%{opacity: 0;}
}