26

I want to achieve the following effect with CSS:

enter image description here

This star icon is a font. I would like to define the width of the orange background by percents, so 50% should be the perfect half of the star.

For now, I did the following:

<div class="container">
    <span class="star star-under fa fa-star"></span>
    <span class="star star-over fa fa-star"></span>
</div>

And:

.container
{
    font-size: 200px;
    height: 300px;
    position: relative;
    width: 100%;
}

.star
{
    display: inline-block;
    left: 0;
    position: absolute;
    top: 0;
}

.star-under
{
    color: #ddd;
}

.star-over
{
    color: #f80;
    overflow: hidden;
    width: 30%;
}

The problem is that I need to provide the width and height in order to use % of width. And if I skip the container's width and height, it displays nothing, because it contains absolutely positioned children.

This % value is calculated on server side, so I'd rather keep it inline, like this:

<span class="star star-over fa fa-star" style="width: 62%;"></span>

What is the most flexible way to do this? By most flexible I mean the one that doesn't make it necessary to provide any width nor height.

Stickers
  • 75,527
  • 23
  • 147
  • 186
Robo Robok
  • 21,132
  • 17
  • 68
  • 126

1 Answers1

11

You can set the container to display:inline-block, and only set the top icon to position:absolute.

.container {
  font-size: 200px;
  position: relative;
  display: inline-block;
}
.star-under {
  color: #ddd;
  vertical-align: top;
}
.star-over {
  color: #f80;
  position: absolute;
  left: 0;
  top: 0;
  width: 70%;
  overflow: hidden;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<div class="container">
  <span class="star star-under fa fa-star"></span>
  <span class="star star-over fa fa-star"></span>
</div>
Stickers
  • 75,527
  • 23
  • 147
  • 186
  • I actually tried similar way, but got my results unequal. The text positions didn't match if one was put without `position: absolute` and the second was. I need to inspect all inherited styles. – Robo Robok Feb 23 '16 at 00:56
  • 1
    I noticed that too ealier, so I added `vertical-align` and it seems to be working good. – Stickers Feb 23 '16 at 00:58
  • Ha, that's an idea! I will try that and select your answer if it works! Thanks mate. – Robo Robok Feb 23 '16 at 01:01
  • 3
    You can remove the container and just nest the over icon inside the under icon. https://jsfiddle.net/vco9r2rt/4/ – Miguel Mota Feb 23 '16 at 01:08
  • 1
    Thanks a lot, guys :) I needed to keep the container anyway, because I'm having some paddings there, that must stay paddings (not margins). With paddings, my % would be not precise. But now I use my over element inside the under element, which is more convenient. And thanks for `vertical-align`, Pangloss :) – Robo Robok Feb 23 '16 at 01:22