Could we help you? Please click the banners. We are young and desperately need the money
Creating an interactive star rating system can be a daunting task, especially for beginners. Many tutorials and solutions involve JavaScript, which can add unnecessary complexity. However, it's entirely possible to create a functional and visually appealing star rating system using only HTML and CSS. In this tutorial, we'll show you how to achieve this with a step-by-step guide. The full working example can be found on JSFiddle.
Using pure CSS for star ratings has several benefits:
The HTML structure consists of a <div>
containing radio buttons and labels. Here's the basic structure:
<div class="rating-stars-wrapper">
<input type="radio" name="rating-stars" value="5" id="id-5">
<label for="id-5"></label>
<input type="radio" name="rating-stars" value="4" id="id-4" checked>
<label for="id-4"></label>
<input type="radio" name="rating-stars" value="3" id="id-3">
<label for="id-3"></label>
<input type="radio" name="rating-stars" value="2" id="id-2">
<label for="id-2"></label>
<input type="radio" name="rating-stars" value="1" id="id-1">
<label for="id-1"></label>
</div>
Each radio button represents a rating value from 1 to 5. The corresponding labels will be used to display the stars.
The CSS is where the magic happens. Let's break down the key parts of the styling:
.rating-stars-wrapper {
display: flex;
flex-direction: row-reverse;
justify-content: center;
width: fit-content;
}
We use flex-direction: row-reverse
to reverse the order of the radio buttons. This allows us to target the stars after the checked one.
input[type="radio"] {
display: none;
}
The radio buttons are hidden from view but remain functional.
label {
cursor: pointer;
font-size: 40px;
color: red;
}
label:before {
content: '\2606'; /* Unicode for empty star */
position: relative;
}
The labels are styled to look like stars. The :before
pseudo-element is used to insert the star character.
input[type="radio"]:checked ~ label:before {
content: '\2605'; /* Unicode for filled star */
opacity: 0.7;
}
When a radio button is checked, the corresponding star and all previous stars are filled.
.rating-stars-wrapper label:hover:before,
.rating-stars-wrapper label:hover ~ label:before {
content: '\2605';
opacity: 0.7;
}
The hover effect changes the stars to filled when hovered over.
.rating-stars-wrapper:not(:hover) input[type="radio"]:checked ~ label:before,
.rating-stars-wrapper:hover input[type="radio"]:hover ~ label:before {
opacity: 1;
}
This ensures that the checked star remains filled even when not hovered over.
By using this pure CSS solution, you can create a star rating system that is simple, efficient, and accessible. This method leverages the power of CSS to handle interactivity without the need for JavaScript, making it an excellent choice for web developers of all levels.