纯CSS实现IOS风格开关

@Pelom  November 9, 2021

示例

实现

开关按键的原型是一个复选框
它的默认样式是这样的

<input type="checkbox">

CSS中的选择器语法为

input[type=checkbox]{

}

type值为"checkbox"<input>
先去掉它的默认样式appearance: none;
需要注意的是,复选框默认采用的是怪异盒模型(即widthheight包含paddingborder),因此需要用box-sizing: content-box;将其设置为标准盒模型
再设置border-radius使其变成圆角矩形

input[type=checkbox]{
    appearance: none;
    box-sizing: content-box;
    width: 3.5rem;
    height: 1.5rem;
    border: 1px solid silver;
    outline: none;
    background-color: white;
    border-radius: .75rem;
}

通过::before::after伪元素来来创建滑块,只需要content: ''就可以当作<div>使用
再通过:checked伪类处理在不同点击状态下的样式
加上适当动画过渡

input[type=checkbox]{
    transition: background-color .3s, border .3s;
}
input[type=checkbox]:checked{
    border-color: limegreen;
    background-color: limegreen;
}
input[type=checkbox]::before{
    content:'';
    position: absolute;
    top: 0;
    left: 0;
    width: 1.5rem;
    height: 1.5rem;
    border-radius: .75rem;
    background-color: white;
    box-shadow: 0 0 2px gray;
    transition: left .3s ease;
    z-index: 1;
}
input[type=checkbox]:checked::before{
    left: calc(100% - 1.5rem);
}

同样使用伪元素的content,还可以添加字样

input[type=checkbox]::after{
    content: 'off';
    position: absolute;
    height: inherit;
    right: .4rem;
    color: grey;
}
input[type=checkbox]:checked::after{
    content: 'on';
    left: .4rem;
    color: whitesmoke;
}

添加新评论