css3修改input[type=radio]样式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39072332/article/details/82789668

在项目中经常,需要使用单选按钮input[type=radio],但是浏览器的默认样式可能与我们需要实现的样式差距很大,可以使用css3来实现想要达到的效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
    div {
            position: relative;
            line-height: 30px;
        }

        input[type="radio"] {
            width: 20px;
            height: 20px;
            opacity: 0;
        }

        label {
            position: absolute;
            left: 5px;
            top: 3px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 1px solid #999;
        }

        /*设置选中的input的样式*/
        /* + 是兄弟选择器,获取选中后的label元素*/
        input:checked+label {
            background-color: #349EDF;
            border: 1px solid #349EDF;
        }

        input:checked+label::after {
            position: absolute;
            content: "";
            width: 5px;
            height: 10px;
            top: 3px;
            left: 6px;
            border: 2px solid #fff;
            border-top: none;
            border-left: none;
            transform: rotate(45deg)
        }
    </style>
</head>

<body>
    <div>
        <input id="item1" type="radio" name="item" value="item1" checked>
        <label for="item1"></label>
        <span>选项一</span>
    </div>
    <div>
        <input id="item2" type="radio" name="item" value="item2">
        <label for="item2"></label>
        <span>选项二</span>
    </div>
</body>
</html>

实际效果如图:

猜你喜欢

转载自blog.csdn.net/weixin_39072332/article/details/82789668