Earlier I’ve written how you can enlarge an image on hover in Vue.js by dynamically toggling a CSS class. Here I’ll show you how you can shrink or make an image smaller on hover. The idea is to have an image with some default height initially. Then have a reactive state which will decide whether the image is shrunk or not. Whenever you hover your mouse over the image, the state would be set to true. And if you move your mouse out of the image, it’d be set to false. This reactive state is then bind to a CSS class of two different heights. Here’s the code I’ve written to demonstrate the same:
<template>
<div id="app">
<div>
<img
:src="$options.imgUrl"
:class="{
'img-default-size': true,
'img-shrunk-size': imageShrunk,
}"
@mouseover="shrinkImage"
@mouseout="enlargeImage"
/>
</div>
<div class="np-credits">wwww.nightprogrammer.com</div>
</div>
</template>
<script>
export default {
name: "ImageShrink",
created() {
this.$options.imgUrl =
"https://images.unsplash.com/photo-1658148900843-bf9d17c2ca2e";
},
data() {
return {
imageShrunk: false,
};
},
methods: {
enlargeImage() {
this.imageShrunk = false;
},
shrinkImage() {
this.imageShrunk = true;
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
}
.img-default-size {
height: 300px;
transition: all 0.2s;
}
.img-shrunk-size {
height: 270px;
transition: all 0.2s;
}
.np-credits {
font-size: 12px;
margin-bottom: 12px;
color: #4b4b4b;
}
</style>
Code language: HTML, XML (xml)
You can find a working copy of the above code from my repos here: