0

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?

3 Answers 3

3

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!

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

2 Comments

But what if I wanted to set 2 CSS properties? I know I can just define a style object in data and use that. But what if I wanted to place it inline instead of referencing an object from data? For example, the following code didn't work: v-bind:style="{ top,visibility: !ended ? '20%,visible' : '80%,hidden'}" How would I rewrite this to make it work?
@Vktr Similar to normal objects, you have to input different properties as { prop1: val1, prop2: val2, prop3: val3 } and so on... So to add the visibility property to the above code: <img src="../assets/myimg.png" id="myimg" v-bind:style="{ top: !ended ? '20%' : '80%', visibility: !ended ? 'visible' : 'hidden' }"> .
0

Try writing it inside brackets,

<img src="../assets/myimg.png" id="myimg" v-bind:style="[!ended ? {'top':'20%'} : {'top':'80%'}]">

Comments

0

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%'
    }
  }
}

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.