0

I'm trying to visually represent results of a poll inside bars.

I can't manage to display score bars into items properly.

Here is what I have so far :

#poll {
  max-width: 480px;
}

.score {
  float: right;
}

.item {
  border: 1px solid grey;
  padding: 5px;
  margin: 3px 0;
}

.bar {
  display:block;
  background: #61CE3C;
  height: 100%;
  position: relative;
  z-index: -1;
}
<div id="poll">
  <div class="item">
    <span class="bar" style="width:84.6%;"> </span>
    <span class="title">More than 10</span>
    <span class="score">84.6%</span>
  </div>
  <div class="item">
    <span class="bar" style="width:0;"> </span>
    <span class="title">Between 5 and 10</span>
    <span class="score">0%</span>
  </div>
  <div class="item">
    <span class="bar" style="width:15.4%;"> </span>
    <span class="title">Less than 5</span>
    <span class="score">15.4%</span>
  </div>
</div>

How to display background bar behind title and score as fractional width of parent item?

2 Answers2

1

Simply use a background linear gradient:

#poll {
  max-width: 480px;
}

.score {
  float: right;
}

.item {
  border: 1px solid grey;
  padding: 5px;
  margin: 3px 0;
}
<div id="poll">
  <div class="item" style="background: linear-gradient(to right, #a6e2ae 84.6%, transparent 0px);">
    <span class="title">More than 10</span>
    <span class="score">84.6%</span>
  </div>
  <div class="item" style="background: linear-gradient(to right, #a6e2ae 0%, transparent 0px);">
    <span class="title">Between 5 and 10</span>
    <span class="score">0%</span>
  </div>
  <div class="item" style="background: linear-gradient(to right, #a6e2ae 15.4%, transparent 0px);">
    <span class="title">Less than 5</span>
    <span class="score">15.4%</span>
  </div>
</div>
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
0

You can give the item a flex display and remove the z-index:-1

#poll {
  max-width: 480px;
}

.item {
  border: 1px solid grey;
  padding: 5px;
  margin: 3px 0;
  width: 100%;
  display: flex;
}

.score {
  margin-left: auto;
}

.bar {
  background: #61CE3C;
}
<div id="poll">
  <div class="item">
    <span class="bar" style="width:84.6%;"> </span>
    <span class="title">More than 10</span>
    <span class="score">84.6%</span>
  </div>
  <div class="item">
    <span class="bar" style="width:0;"> </span>
    <span class="title">Between 5 and 10</span>
    <span class="score">0%</span>
  </div>
  <div class="item">
    <span class="bar" style="width:15.4%;"> </span>
    <span class="title">Less than 5</span>
    <span class="score">15.4%</span>
  </div>
</div>
Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35