【问题标题】:CSS - Custom styling on radio buttonCSS - 单选按钮上的自定义样式
【发布时间】:2016-11-17 23:32:32
【问题描述】:

我在这里有一个 jsfiddle - https://jsfiddle.net/5qmnptuk/4/

我正在尝试创建一个自定义单选按钮。

我隐藏了单选按钮,然后在标签上使用 :after 创建了新单选按钮。

我正在尝试使用 :checked 来设置点击的样式,但它不起作用

谁能明白为什么这不起作用。

    .form-group{
        margin-top: 30px;
    }

    label{
        cursor: pointer;
        display: inline-block;
        position: relative;
        padding-right: 25px;
        margin-right: 15px;
    }

    label:after{
        bottom: -1px;
        border: 1px solid #aaa;
        border-radius: 25px;
        content: "";
        display: inline-block;
        height: 25px;
        margin-right: 25px;
        position: absolute;
        right: -31px;
        width: 25px;
    }

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

    input[type=radio]:checked + label{
        content: \2022;
        color: red;
        font-size: 30px;
        text-align: center;
        line-height: 18px; 
    }

【问题讨论】:

    标签: css radio checked


    【解决方案1】:

    你的代码有几个问题:

    1 - 您的输入需要 label 之前

    +~ CSS 选择器仅在 DOM 中的元素之后选择兄弟元素,因此您需要在标签之前输入。

    2 - 您的标签未分配给输入

    要分配标签,请使用for 属性,并给输入一个ID:

      <div class="form-group">
        <input type="radio" id="custom" />
        <label for="custom">Label</label>
      </div>
    

    3 - 伪元素的内容缺少引号。

    4 - 您没有将样式应用于标签的 after 元素,而是将它们直接应用于标签:

     input[type=radio]:checked + label{
        content: \2022;
        color: red;
        font-size: 30px;
        text-align: center;
        line-height: 18px; 
    }
    

    选择标签,而:

    input[type=radio]:checked + label:after{
        content: "\2022";
        color: red;
        font-size: 30px;
        text-align: center;
        line-height: 18px; 
    }
    

    选择after 元素

    Updated, working JSFiddle

    【讨论】:

    • 雅各布的好答案。
    • 还有一个。所有radio 必须具有相同的属性name 才能允许用户更改选择。
    • @spirit 好点,但这与问题无关,所以我没有将其添加到答案中:)
    • @JacobGray,也许这不是真正的相对问题,但这个问题很可能是他的下一个问题=)
    【解决方案2】:

    更新了 fiddle 我为收音机和标签需求添加了 id

    for="radioId" 
    

    能够像那样工作

    标签也需要在单选按钮之后

    【讨论】:

      猜你喜欢
      • 2015-10-04
      • 2013-06-10
      • 2014-01-22
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 2012-05-23
      • 1970-01-01
      相关资源
      最近更新 更多