0

I want to create a component with some CSS parameters. I know I'm not able to do something like this

<template>
  <div id="textContainer">
    {{ content }}
  </div>
</template>

<script>
export default {
  props: {
    content: String,
    textAlign: String
  }
};
</script>

<style scoped>
#textContainer {
  text-align: {{textAlign}}; // this won't work
}
</style>

but I thought about creating a component that deals with the css parameters in the HTML code like this example

<template>
  <div id="textContainer" :style="'text-align: {{textAlign}}'">
    this should be right aligned
  </div>
</template>

<script>
export default {
  props: {
    textAlign: String
  }
};
</script>

<style scoped>
#textContainer {
  text-align: center;
}
</style>

and consume it with

<MyComponent textAlign="right" />

I don't know if this won't work or my syntax is wrong. I provide a working example

https://codesandbox.io/s/my002w6oqy

and would like to know if there is a way to create components with dynamic css parameters. Otherwise I would have to create components which only differ in their css style.

1
  • 1
    I would prefer passing CSS classes instead of styles. What will happen if you want to change the style in future? You can name classes as themes preferable e.g. theme_a, theme_b Commented Dec 14, 2018 at 19:46

1 Answer 1

1

You can use the object syntax:

<template>
  <div id="textContainer" :style="{ textAlign }">
    this should be right aligned
  </div>
</template>

<script>
export default {
  props: {
    textAlign: String
  }
};
</script>

https://codesandbox.io/s/wnpl6zvnlw

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

2 Comments

thanks for your help. Your example works fine but I don't get why it works. How does textAlign match to text-align?
Vue convert camel case textAlign to kebab-case text-align during the compiling process. And also notice { textAlign } is short for { textAlign: textAlign } and then camel case to kebab-case { 'text-align': textAlign }.

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.