自定义 checkbox 和 radio

2022-10-09,,

在页面中我们经常会使用到 checkbox 和 radio,但是,部分浏览器显示的效果并不能让我们满意,因此想通过一种方式,更改其样式。
这里使用到的就是使用 label,结合 before 实现样式的更改。
完整代码:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定制checkbox 与 radio</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-size: 1rem;
        }

        main {
            padding: 100px;
            display: flex;
            align-items: center;
        }

        input[type=checkbox],
        input[type=radio] {
            display: none;
        }

        input[type=checkbox]+label,
        input[type=radio]+label {
            margin-right: 10px;
            text-align: center;
            cursor: pointer;
            display: flex;
            align-items: center;
        }

        input[type=checkbox]+label::before,
        input[type=radio]+label::before {
            content: '';
            width: 1em;
            height: 1em;
            border: 1px solid #ccc;
            display: inline-block;
            box-sizing: border-box;
            padding: 2px;
            margin-right: 2px;
            border-radius: 2px;
            background-color: #fff;
        }
        input[type=radio]+label::before {
            border-radius: 2em;
        }

        input[type=checkbox]:checked+label::before,
        input[type=radio]:checked+label::before {
            background-color: green;
            background-clip: content-box;
            border-color: green;
        }

    </style>
</head>

<body>
    <main>
        <input type="checkbox" id="ck_1">
        <label for="ck_1">test</label>
        <input type="checkbox" id="ck_2" checked>
        <label for="ck_2">test</label>
        <input type="checkbox" id="ck_3">
        <label for="ck_3">test</label>
    </main>
    <main>
        <input type="radio" id="ra_1" name="aaa">
        <label for="ra_1">boy</label>
        <input type="radio" id="ra_2" name="aaa">
        <label for="ra_2">girl</label>
    </main>
</body>

</html>

效果图:

这样相比之前就好看那么一点点,如果引入字体图标,对 css 稍作更改,就能基本满足自己的需求了。

《自定义 checkbox 和 radio.doc》

下载本文的Word格式文档,以方便收藏与打印。