Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda