如何使用 CSS 创建"切换开关"(开/关按钮)?
cssweb developmentfront end technology更新于 2025/11/26 15:40:17
要使用 CSS 创建切换开关,代码如下 −
示例
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
span {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
span:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + span {
background-color: rgb(85, 21, 138);
}
input:focus + span {
box-shadow: 0 0 1px rgb(255, 77, 211);
}
input:checked + span:before {
transform: translateX(26px);
}
span.round {
border-radius: 34px;
}
span.round:before {
border-radius: 50%;
}
</style>
</head>
<body>
<h1>Toggle Switch Example</h1>
<label class="switch">
<input type="checkbox">
<span class="round"></span>
</label>
<label class="switch">
<input type="checkbox" checked>
<span class="round"></span>
</label>
</body>
</html>
输出
上述代码将产生以下输出 −

相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

