纯 CSS 实现一个 Switch 开关

2015/02/24 | 1分钟阅读 | 更新于 2015/02/24

读了一些switch开关的代码,发现大家的代码差不多都是一个div套一个input后跟一个label,通过 input:checked 选择 label 改变后者的位置 我也写了一个简化版的


主要代码

css部分

.switch {
	margin:10px auto; 
	width:120px;
	height:40px;
	background-color: #abcdef;
}
.switch input {
	width: 0px;
	height: 0px;
	/*position:absolute;*/
	float: left;
	width: 100%;
	height: 100%;
	opacity: 0.3; /*使用的时候改为0以隐藏checkbox*/
}
.switch label {
	display: block;
	position:relative;
	width:40px;
	height:40px;
	background-color: #66aadd;
	left:0px;
	top:0px;
	transition-duration: .2s;
}
.switch input:checked ~ label {
	left:80px;
}

html部分

<div>
	<div class="switch">
 	<input type="checkbox" id="control">
		<label for="control" ></label>
</div>
<br />
<div> <!--再来一个-->
	<div class="switch">
 	<input type="checkbox" id="control">
		<label for="control" ></label>
</div>
<br />
<div> <!--再来一个-->
	<div class="switch">
 	<input type="checkbox" id="control">
		<label for="control" ></label>
</div>

截图

IE11

Firefox


然后

  • 不兼容早期版本的ie
  • webkit内核浏览器好像需要需要加前缀-webkit-transition-duration: .2s

© 2026 香蕉引擎故障报告

🌱 Powered by Hugo with theme Dream.

关于

要怎么介绍自己呢,🤔。

很早以前是作为 Web 前端在学习的,但是工作第一年就成为了全干工程师。喜欢尝试各种东西,什么都会一点。

一直很喜欢 Ebiten 游戏引擎 ,特别简洁,用它做过一些小东西,可以查看这个分类 。另外特别推荐这个木鱼 ,是一个相对完整的小玩意儿,包含手搓的一个简单的 UI 框架;支持鼠标和键盘操作;有多语言和主题切换功能;同时支持 Web 端和客户端。它的源代码在 bin16/wooden-fish

主题

网站基于 Hugo,当前使用的是 hugo-theme-dream 主题的修改版 ,根据我的需要,做了一些对 PaperMod 的兼容。

我自己也写过主题 ,但是没有别人写的好看。

正在从我的笔记中往外搬运内容

等待更新:

  • 从《锈湖》中学了些什么东西
  • 我拿 React 写解谜游戏的经过
  • 基于 Pocketbase 的 Pocket Memos
  • 数独!