使用SCSS语法自定义单选按钮

时间:2019-04-03 07:18:49

标签: html css sass radio-button

我自定义了单选按钮,但我想使用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时,我的按钮消失了。我看不出是什么问题。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

您必须使用+选择器:

& + 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;
        }
    }

答案 1 :(得分:0)

首先,您的CSS代码无效,因为您不能在CSS中将变量用作$margin-small

第二,我使用convertor来完成

$margin-small:15px;

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