# 纯CSS制作轮播图 **Published by:** [an7](https://paragraph.com/@myairdrop/) **Published on:** 2022-04-19 **URL:** https://paragraph.com/@myairdrop/css ## Content 原理:通过label控制type为radio的input中的checked属性,当对应位置的radiochecked时,做出相应动作,动作为将轮播图片进行位移到可见区域进行展示。HTML代码<ul class="slides"> <input type="radio" id="control-1" name="control" checked> <input type="radio" name="control" id="control-2"> <input type="radio" name="control" id="control-3"> 注释:此input用来提供checked用于逻辑判断 <li class="slide">1</li> <li class="slide">2</li> <li class="slide">3</li> 注释:此li为模拟图片展示 <div class="controls-visible"> <label for="control-1"></label> <label for="control-2"></label> <label for="control-3"></label> 注释:此label通过for属性关联对应的input,实现点击label切换对应input的checked </div> </ul> CSS代码body{ display:flex; justify-content:center; align-items:center; min-height:100vh; } ul.slides{ position:relative; width:600px; height:280px; list-style:none; margin:0; padding:0; background-color:#eee; overflow:hidden } li.slide{ margin:0; padding:0; width:inherit; height:inherit; position:absolute; top:0; left:0; display:flex; justify-content:center; align-items:center; font-size:123px; color:white; transition:0.5s transform ease-in-out; } 注释:创建三个不同背景色同样大小的区块并排,模拟轮播图片 .slide:nth-of-type(1){ background-color:yellow; } .slide:nth-of-type(2){ background-color:red; left:100% } .slide:nth-of-type(3){ background-color:blue; left:200% } input[type="radio"]{ position:relative; z-index:100; display:none; } .controls-visible{ position:absolute; width:100%; bottom:12px; text-align:center; } .controls-visible label{ display:inline-block; width:10px; height:10px; background-color:white; border-radius:50%; margin:0 3px; border:2px solid #fff; } .slides input[type="radio"]:nth-of-type(1):checked ~ .controls-visible label:nth-of-type(1){ background-color:gray; } .slides input[type="radio"]:nth-of-type(2):checked ~ .controls-visible label:nth-of-type(2){ background-color:green; } .slides input[type="radio"]:nth-of-type(3):checked ~ .controls-visible label:nth-of-type(3){ background-color:pink; } .slides input[type="radio"]:nth-of-type(1):checked ~ .slide{ transform:translatex(0%) } .slides input[type="radio"]:nth-of-type(2):checked ~ .slide{ transform:translatex(-100%) } 注释:当第二个radio被checked时,将li往左移一格 .slides input[type="radio"]:nth-of-type(3):checked ~ .slide{ transform:translatex(-200%) } 注释:当第二个radio被checked时,将li往左移一格 演示地址: https://codepen.io/xbox366/pen/KKZbqWj ## Publication Information - [an7](https://paragraph.com/@myairdrop/): Publication homepage - [All Posts](https://paragraph.com/@myairdrop/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@myairdrop): Subscribe to updates