Home  >  Q&A  >  body text

Define the top attribute of v-img in CSS using calculated switches

<p>I want to define the top attribute of v-img based on the current breakpoint of the window. </p> <p>I want to define it like this:</p> <pre class="brush:php;toolbar:false;"><v-img contain id="logo-transparent" :top="logoTop" :width="logoWidth" :src=" logoTransparent" class="hidden-xs-only"></v-img></pre> <p>The calculated properties are as follows:</p> <pre class="brush:php;toolbar:false;">logoTop(){ switch (this.$vuetify.breakpoint.name) { case 'xl': return "-4%" case 'lg': return "-6%" case 'md': return "-8%" case 'sm': return "-8%" case 'xs': return 0 default: return "-4%" } },</pre> <p>The CSS is as follows:</p> <pre class="brush:php;toolbar:false;">#logo-transparent{ z-index: 1; width: 400px; height: 300px; position: absolute; right: -1%; }</pre> <p>But the problem is that v-img does not have a top attribute. </p> <p>I want to use computed properties to define the CSS of an image like this: </p> <pre class="brush:php;toolbar:false;">logoTop(){ return { "--top-property" : switch (this.$vuetify.breakpoint.name) { case 'xl': return 400 case 'lg': return 300 case 'md': return 300 case 'sm': return 200 case 'xs': return 0 default: return 400 } } },</pre> <p>Use it in CSS as follows: </p> <pre class="lang-css prettyprint-override"><code>top : var(--top-property) </code></pre> <p>But it seems I can't use switch in this case. </p> <p>What should I do? </p>
P粉704196697P粉704196697415 days ago463

reply all(2)I'll reply

  • P粉300541798

    P粉3005417982023-08-31 16:51:55

    Your original logoTop computed property can be used in style bindings to set the top position of v-img:

    <template>
      <v-img :style="{ top: logoTop }" ... />
    </template>
    
    <script>
    export default {
      computed: {
        logoTop() {
          switch (this.$vuetify.breakpoint.name) {
            case 'xl': return "-4%"
            case 'lg': return "-6%"
            case 'md': return "-8%"
            case 'sm': return "-8%"
            case 'xs': return 0
            default: return "-4%"
          }
        },
      }
    }
    </script>
    

    Demo

    reply
    0
  • P粉462328904

    P粉4623289042023-08-31 14:24:05

    switchReturns nothing. You should use a variable like this

    logoTop() {
        let topProperty;
        switch (this.$vuetify.breakpoint.name) {
            case 'xl':
                topProperty =  400;
                break;
            case 'lg':
            case 'md':
                topProperty =  300;
                break;
            case 'sm':
                topProperty =  200;
                break;
            case 'xs':
                topProperty =  0;
                break;
            default:
                topProperty = 400;
        }
        return {
            "--top-property" : topProperty
        }
    },
    
    

    reply
    0
  • Cancelreply