Conditional CSS :style in Vue.js

This took me way too long to figure out, so it's going here. 

You do not use v-if, because that only applies to tags, not attributes. 

Instead, you use a ternary operator:

:style="[index === 2 ? {'margin-bottom': '40px'} : {}]"

This is telling us: If the index variable is 2, then change the bottom margin to 40 pixels. Otherwise, keep the bottom margin at the default (hence the empty curly braces). In this case, the default bottom margin is 32 pixels. However, I'm not actually sure where that default margin attribute is coming from. It could be a built-in Vue styling, but more than likely it's trickling down from a higher-level stylesheet. That said, it's irrelevant for the purposes of this post. 

So yay, ternaries finally have a practical use other than showing off for people who try too hard to look smart! This is excellent. 

Comments

Popular posts from this blog

Unleashing my inner Disney Princess ✩₊˚.⋆☾⋆⁺₊✧ at the 2024 Disney Princesses Half Marathon

The 20-something types of Computer Science majors

The Evenstar