首页 > 解决方案 > 在 SCSS 语法中自定义单选按钮

问题描述

我自定义了我的单选按钮,但我想使用 SCSS 使我的代码更简洁。所以我将我的代码从 CSS 更改为 SCSS 但出现了一个问题:

HTML

<input type="radio" name="test" value="value">
<label>
    <span></span>
    Test radio
</label>

CSS

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

input[type="radio"] + label span {
    display: inline-block;
    width: 24px;
    height: 24px;
    margin-right: 6px;
    vertical-align: middle;
    background: url(./radio-sprite.svg) -46px 0 no-repeat;
    background-size: 92px 24px;
    cursor: pointer;
}

input[type="radio"]:checked + label span {
    background: url(./radio-sprite.svg) -69px 0px no-repeat;
    background-size: 92px 24px;
}

input[type="radio"]:disabled + label span {
    background: url(./radio-sprite.svg) -22px 0px no-repeat;
    background-size: 92px 24px;
}

SCSS

input[type="radio"] {
    display: none;

    & > label {
        cursor: pointer;

        span {
            display: inline-block;
            width: 24px;
            height: 24px;
            margin-right: $margin-small;
            vertical-align: middle;
            background: url(./app/shared/assets/icons/radiobtn-sprite.svg) -46px 0 no-repeat;
            background-size: 92px 24px;
            cursor: pointer;
        }
    }

    &:checked + label span {
        background: url(./app/shared/assets/icons/radiobtn-sprite.svg) -69px 0px no-repeat;
        background-size: 92px 24px;
    }

    &:disabled + label span  {
        background: url(./app/shared/assets/icons/radiobtn-sprite.svg) -22px 0px no-repeat;
        background-size: 92px 24px;
    }
}

当我用上面的 SCSS 代码替换我的 CSS 时,我的按钮消失了。我看不出似乎是什么问题。任何帮助,将不胜感激

标签: htmlcsssassradio-button

解决方案


您必须使用+选择器:

& + label {
        cursor: pointer;
        span {
            display: inline-block;
            width: 24px;
            height: 24px;
            margin-right: $margin-small;
            vertical-align: middle;
            background: url(./app/shared/assets/icons/radiobtn-sprite.svg) -46px 0 no-repeat;
            background-size: 92px 24px;
            cursor: pointer;
        }
    }

推荐阅读