Filling a circle border by percent [duplicate]

2019-08-22 21:25发布

问题:

This question already has an answer here:

  • Percent pie chart with css only 2 answers

I tried implementing several guides to creating a circle which fills according to a percentage but i can't seem to get it to work (no animation, only a static CSS circle).

The circle border currently abides to background-image: linear-gradient which i first set to a (90+(360*0.percent))deg and a second one which is set to 90deg. It works well on the first 50% but beyond that it doesn't fill accordingly.

.circle {
  position: relative;
  top: 5px;
  left: 5px;
  text-align: center;
  width: 100px;
  height: 100px;
  border-radius: 100%;
  background-color: #ffffff;
}

.circle-border {
  position: relative;
  text-align: center;
  width: 110px;
  height: 110px;
  margin-left: 30%;
  border-radius: 100%;
  background-color: #E53B3B;
  background-image: linear-gradient(162deg, transparent 50%, #f0f0f0 50%), linear-gradient(90deg, #f0f0f0 50%, transparent 50%);
}
<div class="circle-border">
  <div class="circle">
  </div>
</div>

What values of linear-gradient should be changed when i want the circle to be filled for more than 50%?

回答1:

For first linear part, you can use linear-gradient:(270deg,...) for filling 50% of the circle.

For other linear part, you can increase the angle (270°+) to fill more than 50% of the circle (360° or 0° = 75% of the circle ... 90° = 100% of the circle)

For example: linear-gradient(270deg, black 50%, transparent 50%), linear-gradient(0deg, black 50%, lightgray 50%) combination creates a circle with a lightgray background, filled with seventy-five percent black color. (snippet below)

.circle {
  position: relative;
  top: 5px;
  left: 5px;
  text-align: center;
  width: 100px;
  height: 100px;
  border-radius: 100%;
  background-color: #ffffff;
}

.circle-border {
  position: relative;
  text-align: center;
  width: 110px;
  height: 110px;
  margin-left: 30%;
  border-radius: 100%;
  background-color: #E53B3B;
  background: linear-gradient(270deg, black 50%, transparent 50%), linear-gradient(0deg, black 50%, lightgray 50%)
}
<div class="circle-border">
  <div class="circle">
  </div>
</div>



回答2:

.circle {
  position: relative;
  top: 5px;
  left: 5px;
  text-align: center;
  width: 100px;
  height: 100px;
  border-radius: 100%;
  background-color: #ffffff;
}

.circle-border {
  position: relative;
  text-align: center;
  width: 110px;
  height: 110px;
  margin-left: 30%;
  border-radius: 100%;
  background-color: #E53B3B;
  background-image: linear-gradient(162deg, transparent 100%, #f0f0f0 100%), linear-gradient(90deg, #f0f0f0 -100%, transparent 0%);
}
<div class="circle-border">
  <div class="circle">
  </div>
</div>

Just have to play with the numbers.