1

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>

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.