纯css实现switch开关

首先看看效果

在这里插入图片描述

主要用到以下知识

  • ::after(伪元素——用它实现左右滑动效果)
  • :checked(伪类选择器——用它来实现选中和不选中)

网页结构

<input type="checkbox" class="switch" />

css样式

        .switch {
            -moz-appearance: none;//选中前的input样式
            -webkit-appearance: none;
            position: relative;
            width: 60px;
            height: 25px;
            background: rgb(207, 205, 205);
            border-radius: 10px;
            outline: none;
        }

        .switch::after {
            content: "";//选中前的伪元素样式
            position: absolute;
            width: 40%;
            height: 100%;
            border-radius: 10px;
            left: 0;
            top: 0;
            background: rgb(141, 140, 140);
            transition: all 0.5s;
        }

        .switch:checked {
            background: rgb(55, 218, 136);//选中后的input样式
        }

        .switch:checked::after {
            background: orange;//选中后的伪元素样式
            left: 60%;
        }

提示:主要基于谷歌浏览器实现的效果,如果在其他浏览器效果失败,可能是css兼容性导致的。
css兼容性文档可看

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值