SASS-单击时保持按钮颜色(聚焦,活动)

时间:2020-06-09 22:44:53

标签: sass

仅仅是我的Rails应用程序的样式问题。

我做了一些单选按钮,看起来像普通按钮。单击按钮(并选中单选按钮)后,我想使按钮的背景颜色与悬停颜色相同,但是不起作用。不幸的是,我不是最大的CSS专家。 红色只是用于测试。

HTML:

<label class="btn custom-btn good-outline">
  <%= f.radio_button :reception_feed, 2 %>
  <%= image_tag "smiley_2.svg", size: '48x48' %>
</label>

CSS(首次尝试):

.good-outline {
    border-color: #00e676;
    color: #00e676;
    &:hover {
        background-color: #00e676;
        color: white;
    }    
    input[type=radio]:checked + label {
        background-color: red;
    }
  }

CSS(第二次尝试):

.good-outline {
    border-color: #00e676;
    color: #00e676;
    &:hover {
        background-color: #00e676;
        color: white;
    }    
    &:active, &:focus {
        background-color: red;
    }
  }

如果我在浏览器中分配状态,则说明该状态正常。但这不适用于点击事件。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过稍微更改标记来做到这一点。
由于我不熟悉Rails,因此我将在代码段中使用基本的HTML。

首先,为什么您的首次尝试失败。

您的HTML标记:

<label class="btn custom-btn good-outline">
  <%= f.radio_button :reception_feed, 2 %>
  <%= image_tag "smiley_2.svg", size: '48x48' %>
</label>

您的CSS:

.good-outline { // targets all elements with the class .good-outline (so your label)
    border-color: #00e676;
    color: #00e676;
    &:hover { // targets .good-outline on hover (so your label:hover)
        background-color: #00e676;
        color: white;
    }    
    input[type=radio]:checked + label { 
    // targets a label, next direct sibling to an input radio, all children of a .good-outline
    // in your markup, it doesn't target anything
        background-color: red;
    }
  }

简而言之,input[type=radio]:checked + label不会在您的标记中定位任何内容。

现在,让我们更改标记:

<input type="radio" id="choice-first" name="radio-choice">
<label for="choice-first">This is my first choice</label>
<input type="radio" id="choice-second" name="radio-choice">
<label for="choice-second">This is my second choice</label>

查看标签如何直接成为其对应输入的下一个直接同级标签?
因此,您几乎可以保留CSS(我已经使用普通CSS来添加代码段):

label {
  border-color: #00e676;
  color: #00e676;
}
label:hover {
  background-color: #00e676;
  color: white;
}
input[type=radio]:checked + label {
  background-color: red;
}
<input type="radio" id="choice-first" name="radio-choice">
<label for="choice-first">This is my first choice</label>
<input type="radio" id="choice-second" name="radio-choice">
<label for="choice-second">This is my second choice</label>

现在只需要样式即可使其看起来像您想要的。
您可以隐藏输入并仅保留标签,可以在标签中添加图像,依此类推...