So, I have an image in the middle of the page (where I want it to remain) and while I hold the LMB I want it to get a little bit smaller, then go back to its previous size when released.
Below the code:
$(document).ready(function() {
$("#banana").mousedown(function() {
$("#banana").css("height","70%");
});
$("#banana").mouseup(function() {
$("#banana").css("height","100%");
});
});
.centered {
text-align: center;
display: block;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id = "banana" class = "centered">
<img src="https://via.placeholder.com/150" alt="banana.png">
</div>
</body>
I tried get that target using jQuery (but the position of the image changes and it is not centred anymore).
Thanks in advance!
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
Using object-fit When you add an image to a page using the HTML <img> element, the image will maintain the size and aspect ratio of the image file, or that of any HTML width or height attributes. Sometimes you would like the image to completely fill the box that you have placed it in.
This is very easy to do with CSS only, using the :active
pseudo-selector (that corresponds to "mousedown"). Also why not use Flex for easy centering.
.container {
border: #00f solid 1px;
width: 250px;
height: 250px;
display: flex;
justify-content: center;
align-items: center;
}
.container img {
transition: all 0.3s ease-in-out;
transform: scale(1);
}
.container img:active {
transform: scale(0.8);
}
<div class="container"><img src="https://via.placeholder.com/150"/></div>
Try
transform: scale(0.7)
instead of height. It will be centered and it's more efficient (GPU usage)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With