Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda