1

Is there any option to get data attribute value in Vue css?

<template>
   <p data-background="purple"> TEST </p>
</template>

<style lang="scss">
p {
  background: attr(data-background); //error
  &:after {
     background: attr(data-background); //error
  }
}
</style>

1 Answer 1

1

You could use CSS variables for this case.

new Vue({
  el: '#app',
  data: {
    elStyle: {
      '--background': 'lightblue',
    }
  }
});
p:after {
  content: 'A pseudo element';
  background: var(--background, red); // Red is the fallback value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p :style="elStyle"></p>
</div>

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

3 Comments

The problem is that I can't set background in :before and :after pseudo selectors.
If you need to style pseudo elements, you can handle that with CSS custom properties.
Thanks for answer. Unfortunately I need to support IE11.

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.