jj008
jj008

Reputation: 1083

Inline css on vue component

I'm trying to apply a background-color on a div in vue and I'm able to pass in a hex_code from my data but I want to apply a rgba styling to the background. Is there something wrong with my syntax here?

      <div
        v-for="item in itemList"
        :style="{ 'background-color': `rgba(${ item.hex_code }, 0.5)` }"
        :key="item.id">
     </div>

Upvotes: 1

Views: 2463

Answers (1)

Aurel B&#237;l&#253;
Aurel B&#237;l&#253;

Reputation: 7963

Yes, rgba(hex, opacity) is not allowed in CSS (but it is possible in SCSS), it has to be rgba(red, green, blue, opacity). You want something like:

:style="{ 'background-color': `rgba(${ item.red }, ${ item.green }, ${ item.blue }, 0.5)` }"

See also conversion between RGB and hex.

Edit: Since you are doing this in a bound attribute, you can define a helper function to convert your hex_code to RGB suitable for CSS:

:style="{ 'background-color': `rgba(${hexCodeToCSSRGB(item.hex_code)}, 0.5)` }"

With this helper function (adapted from the linked answer):

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}`
    : "0, 0, 0";
}

Note that this will convert "#ff00aa" to "255, 0, 170", so in your background-color, you would end up with rgba(255, 0, 170, 0.5).

Upvotes: 5

Related Questions