Skip to content

Instantly share code, notes, and snippets.

@Namyalg
Created July 10, 2020 05:31
Show Gist options
  • Save Namyalg/c7f0f39d23c9d001600cd4644638f69b to your computer and use it in GitHub Desktop.
Save Namyalg/c7f0f39d23c9d001600cd4644638f69b to your computer and use it in GitHub Desktop.
Pure CSS Star Rating Input
<form class="rating">
<label>
<input type="radio" name="stars" value="1" />
<span class="icon">★</span>
</label>
<label>
<input type="radio" name="stars" value="2" />
<span class="icon">★</span>
<span class="icon">★</span>
</label>
<label>
<input type="radio" name="stars" value="3" />
<span class="icon">★</span>
<span class="icon">★</span>
<span class="icon">★</span>
</label>
<label>
<input type="radio" name="stars" value="4" />
<span class="icon">★</span>
<span class="icon">★</span>
<span class="icon">★</span>
<span class="icon">★</span>
</label>
<label>
<input type="radio" name="stars" value="5" />
<span class="icon">★</span>
<span class="icon">★</span>
<span class="icon">★</span>
<span class="icon">★</span>
<span class="icon">★</span>
</label>
</form>
$(':radio').change(function() {
console.log('New star rating: ' + this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
.rating {
display: inline-block;
position: relative;
height: 50px;
line-height: 50px;
font-size: 50px;
}
.rating label {
position: absolute;
top: 0;
left: 0;
height: 100%;
cursor: pointer;
}
.rating label:last-child {
position: static;
}
.rating label:nth-child(1) {
z-index: 5;
}
.rating label:nth-child(2) {
z-index: 4;
}
.rating label:nth-child(3) {
z-index: 3;
}
.rating label:nth-child(4) {
z-index: 2;
}
.rating label:nth-child(5) {
z-index: 1;
}
.rating label input {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
.rating label .icon {
float: left;
color: transparent;
}
.rating label:last-child .icon {
color: #000;
}
.rating:not(:hover) label input:checked ~ .icon,
.rating:hover label:hover input ~ .icon {
color: #09f;
}
.rating label input:focus:not(:checked) ~ .icon:last-child {
color: #000;
text-shadow: 0 0 5px #09f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment