Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make image/div smaller when LMB is being pressed?

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!

like image 220
SAndreeaM Avatar asked Jul 17 '20 13:07

SAndreeaM


People also ask

How to fix the image size in div?

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.

How do I fill an image in HTML?

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.


2 Answers

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>
like image 173
Jeremy Thille Avatar answered Sep 28 '22 14:09

Jeremy Thille


Try

transform: scale(0.7)

instead of height. It will be centered and it's more efficient (GPU usage)

like image 37
BloodyMonkey Avatar answered Sep 28 '22 14:09

BloodyMonkey