Search code examples
cssrating-system

CSS star-rating system disappears on selection


Can someone please explain why this css star rating disappears when I click either of two highest ratings? I'm using Chrome and got the code from here: http://code.stephenmorley.org/html-and-css/star-rating-widget/.

/*code from http://code.stephenmorley.org/html-and-css/star-rating-widget/*/

.starRating:not(old) {
  display: inline-block;
  width: 7.5em;
  height: 1.5em;
  overflow: hidden;
  vertical-align: bottom;
}

.starRating:not(old)>input {
  margin-right: -100%;
  opacity: 0;
}

.starRating:not(old)>label {
  display: block;
  float: right;
  position: relative;
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24'><path fill='#fff' stroke='#ccc' d='M 12,2.5 14.4,9.5 21.5,9.5 15.8,13.75 18.5,21.5 12,16.625 5.5,21.5 8.2,13.75 2.5,9.5 9.6,9.5 z'/></svg>");
  background-size: contain;
}

.starRating:not(old)>label:before {
  content: '';
  display: block;
  width: 1.5em;
  height: 1.5em;
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24'><path fill='#9c3' stroke='#682' d='M 12,2.5 14.4,9.5 21.5,9.5 15.8,13.75 18.5,21.5 12,16.625 5.5,21.5 8.2,13.75 2.5,9.5 9.6,9.5 z'/></svg>");
  background-size: contain;
  opacity: 0;
  transition: opacity 0.2s linear;
}

.starRating:not(old)>label:hover:before,
.starRating:not(old)>label:hover~label:before,
.starRating:not(:hover)> :checked~label:before {
  opacity: 1;
}

.ratingdiv {
  width: 100%;
  text-align: center;
  background-color: #DCDFE6;
}
<div class="ratingdiv"><br /><br />
  <span class="starRating">
          <input id="rating5" type="radio" name="<?php echo $name; ?>" value="5">
          <label for="rating5" title="outstanding!">5</label>
          <input id="rating4" type="radio" name="<?php echo $name; ?>" value="4">
          <label for="rating4" title="good!">4</label>
          <input id="rating3" type="radio" name="<?php echo $name; ?>" value="3">
          <label for="rating3" title="ok">3</label>
          <input id="rating2" type="radio" name="<?php echo $name; ?>" value="2">
          <label for="rating2" title="meh">2</label>
          <input id="rating1" type="radio" name="<?php echo $name; ?>" value="1">
          <label for="rating1" title="yuck!">1</label>
        </span><br /></div>


Solution

  • Your style margin-right: -100%; is messing things up, and when you click on the last 2 you aren't really clicking on what you think you are.

    To fix this simply remove this style then give the input's a style of position: absolute; so they don't take up space in the DOM.

        .starRating:not(old) > input{
             /*margin-right: -100%; Remove This*/
              position: absolute; /*Add this*/
              opacity      : 0;
          }
    

    See here for a demo