Jarrod
Jarrod

Reputation: 1705

Why is this :checked selector not working?

In the example below, why does the selected star and all the stars before it not stay yellow?

@import url(//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css);

.rating {
  display: inline;
  border: none;
}

.rating > label > input {
  margin: 0px;
}

.rating > label:before {
  margin: 0px;
  font-size: 1em;
  font-family: FontAwesome;
  display: inline-block;
  content: "\f005";
}

.rating > label { 
  color: #ddd;
}

.rating > input:checked ~ label, /* show gold star when clicked */
.rating:hover label { color: #FFD700; } /* hover previous stars in list */
.rating:not(:checked) > label:hover { color: #FFD700; } /* hover current star */
.rating:not(:checked) > label:hover ~ label { color: #ddd;  } /* un-hover stars after current star */
<form>
  <fieldset class="rating">
    <label for="radio1"><input id="radio1" type="radio" value="1"></label>
    <label for="radio2"><input id="radio2" type="radio" value="2"></label>
    <label for="radio3"><input id="radio3" type="radio" value="3"></label>
    <input type="submit" value="Submit">
  </fieldset>
</form>

The lines of code that are causing the problem in my code are:

/* css */  

.rating > input:checked ~ label, /* show gold star when clicked */
.rating:hover label { color: #FFD700; } /* hover previous stars in list */

I can't figure out why the selectors aren't working as intended.

Please help!

Upvotes: 2

Views: 1060

Answers (2)

Muhammad Hamada
Muhammad Hamada

Reputation: 725

A working JSFiddle https://jsfiddle.net/LeoAref/s3btcwjg/

Here we can use the Adjacent sibling CSS selector +

.rating input:checked + label,
.rating input:hover + label,
.rating label:hover { color: #FFD700; }

And edit the HTML to be like:

<form>
    <fieldset class="rating">
        <input id="radio1" type="radio" name="radio" value="1"><label for="radio1"></label>
        <input id="radio2" type="radio" name="radio" value="2"><label for="radio2"></label>
        <input id="radio3" type="radio" name="radio" value="3"><label for="radio3"></label>
        <input type="submit" value="Submit">
    </fieldset>
</form>

Upvotes: 1

Amin Jafari
Amin Jafari

Reputation: 7207

because your checkbox isn't a child of .rating, you've wrapped it in a label so your code must be you need to take your input out of the label:

<input id="radio1" type="radio" value="1"><label for="radio1"></label>

and then change your css to:

.rating > input:checked + label{}

Upvotes: 2

Related Questions