Reputation: 89
In Vue, I'm trying to use style binding for the CSS "top" property of an HTML image element:
<img src="../assets/myimg.png" id="myimg" v-bind:style="[!ended ? 'top:20%' : 'top:80%']">
Here's the CSS for the image:
#myimg{
position: absolute;
width: 100px;
height: 10px;
left: 10%;
}
"ended" is just a prop that this component receives from its parent. If it's false, the "top" property of the image should be 20%, otherwise, it should be 80%.
Unfortunately, the image stays at the same position regardless of whether "ended" is true or false. How can I resolve this?
Upvotes: 0
Views: 708
Reputation: 408
Here's the complete docs for style binding in Vue.js:
https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax-1
In your case, you can use the object syntax:
<img src="../assets/myimg.png" id="myimg" v-bind:style="{ top: !ended ? '20%' : '80%'}">
Hope this helps!
Upvotes: 3
Reputation: 624
Altenatively you can use this method:
<img src="../assets/myimg.png" id="myimg" v-bind:style="'top:' + (!ended ? '20%' : '80%')">
Or if you want to use es6 template literals:
<img src="../assets/myimg.png" id="myimg" v-bind:style="`top: ${!ended ? '20%' : '80%'}`">
The third altenative would be to add the dynamic style to a computed property as follows:
<img src="../assets/myimg.png" id="myimg" v-bind:style="dynamicStyle">
then in your script add the following code:
computed: {
dynamicStyle() {
return {
top: !this.ended ? '20%' : '80%'
}
}
}
Upvotes: 0
Reputation: 1348
Try writing it inside brackets,
<img src="../assets/myimg.png" id="myimg" v-bind:style="[!ended ? {'top':'20%'} : {'top':'80%'}]">
Upvotes: 0