2

I'm styling labels to take place of the standard browser-defined radio button controls. I have a :hover style and a :checked style for the labels.

But it's not clear at a glance whether clicking a button will "uncheck" the currently-checked button. So I would like to change the style of the checked label when another label is hovered.

I have coded an example (JSFiddle).

Current Behavior:

(My screenshot tool removed it, but the cursor is over Radio Button Three. Radio Button One is checked.)

enter image description here

Desired Behavior:

enter image description here

HTML:

<form type="post">
  <input type="radio" name="group" id="radio1" /> 
  <label for="radio1">Radio Button One</label>

  <input type="radio" name="group" id="radio2" /> 
  <label for="radio2">Radio Button Two</label>

  <input type="radio" name="group" id="radio3" /> 
  <label for="radio3">Radio Button Three</label>

  <input type="radio" name="group" id="radio4" /> 
  <label for="radio4">Radio Button Four</label>
</form>

CSS:

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

input[type="radio"] + label {
  display: block;
  width: 200px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  background-color: white;
}

input[type="radio"] + label:hover {
  background-color: blue;
  color: white;
}

input[type="radio"]:checked + label {
  background-color: red;
  color: white;
}

If I have to use JS, I will, but pure CSS is preferable.

crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81

2 Answers2

3

Unless the selected element is descendant or adjacent you will have difficulty doing this with CSS due to the cascading nature. However if your form has a defined bounding box, you could cheat by taking advantage of the parent's :hover state with CSS such as this:

form:hover input[type="radio"]:checked + label {
  background-color: pink;
}

It is a bit of a hack, but it may give you the desired effect. I hope this helps.

Koda

Kodaloid
  • 1,211
  • 11
  • 19
0

Assuming that Kodaloid is correct, and there's no pure CSS solution, here's a way to accomplish this effect with jQuery (JSFiddle).

I'll have to use this since the form I'm working on has whitespace between buttons.

Add an additional class for the checked label to make it pink:

input[type="radio"]:checked + label.otherhover {
    background-color: pink;
}

Use jQuery to toggle the class at the appropriate times:

$("input[type='radio'] + label").hover(
    function () {
        if (!$("#" + this.htmlFor).is(":checked")) {
            $("input[type='radio']:checked + label").addClass("otherhover");
        }
    }, 
    function () {
        if (!$("#" + this.htmlFor).is(":checked")) {
            $("input[type='radio']:checked + label").removeClass("otherhover");
        }
    }
);
crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81