Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
How to dynamically calculate gradient percentage

I have an array which has dynamic values from server

let arr = ['#eee','#fff','#aaa']
or sometimes,
let arr = ['#eee','#fff','#aaa','#eee','#fff','#aaa']

Now, I need to calculate the gradient values for equal distribution of colors. I did something like below which is giving some wrong value.

let arr = ['#eee','#fff','#aaa','#eee','#fff','#aaa']

let gper = parseFloat(100/arr.length)

let c_arr = arr.map((k, i) => {  return `${k} ${parseFloat(gper * i--)}% ${parseFloat(gper * i)}%`})
               .toString()
               
console.log(`linear-gradient(to left, ${c_arr})`)

Is there a best way to fix this

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you want even distribution of colors in your gradient, it is not necessary to specify percentage at all. The browser does this by default.

You can simply do something like this:

`linear-gradient(to left, ${arr.join()})`
about 4 years ago · Juan Pablo Isaza Report

0

There is just a slight alteration needed to the calculation - in the question the first value went negative.

This snippet spells it out in a loop just to make it a bit clearer - the values need to start at 0 not -gper.

let arr = ['#eee', '#fff', '#aaa', '#eee', '#fff', '#aaa']

let gper = parseFloat(100 / arr.length)

let c_arr = '';
for (let i = 0; i < arr.length; i++) {
  c_arr += ((i == 0) ? '' : ', ') + arr[i] + ' ' + i * gper + '%' + ' ' + (i + 1) * gper + '%';
}
console.log(`linear-gradient(to left, ${c_arr})`);

The result is:

linear-gradient(to left, #eee 0% 16.666666666666668%, #fff 16.666666666666668% 33.333333333333336%, #aaa 33.333333333333336% 50%, #eee 50% 66.66666666666667%, #fff 66.66666666666667% 83.33333333333334%, #aaa 83.33333333333334% 100%)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!