'How to scale element in pixel with CSS? [duplicate]
Elements can be scaled with transform: scale(sx)
, where sx
is the (unit-less) scale factor. Is there some way to scale an element down by a certain number of pixel (without knowing its width).
Edit
I would like to resize elements of different sizes, like buttons, down when they are pressed. However, applying the same scale factor, say scale(.95)
, on all buttons leads to the bigger (smaller) ones to be scaled too much (little). So, what I would like to do is resize all elements when pressed absolutely, i.e. by a certain number of pixel or em or so.
Solution 1:[1]
This is how you could scale the width using vanilla JavaScript
const reduction=10;//in pixels
let button = document.querySelector("#myButton");
button.addEventListener("click",(event)=>{
let style=window.getComputedStyle(button);
let realWidth=parseInt(style.width);
console.log(realWidth);
let newWidth=realWidth-reduction;//some redundancy here
button.style.width=`${newWidth}px`;//this changes the actual width property. With jQuery it would be even easier.
},false);
#myButton{
width:300px;
height:50px;
}
<button id="myButton">Click here to resize</button>
Solution 2:[2]
The only way I would know (with css only) is if you do the following:
This only works as long as it's width and height are not dependent on the elements content
- Surround the element you want to scale with an element that represents the default size. This can either be set in pixels or as a percentage or whatever scale it choses (like auto)
- On
:hover
use the csscalc
function to docalc(100% - <number><em|rm|px|%>)
to scale it by any value and unit available in css.
<div class="button-size">
<button>
Hover me please
</button>
</div>
.button-size
{
width: 300px;
height: 450px;
}
.button-size button
{
width: 100%;
height: 100%;
margin: 8px;
}
.button-size button
{
transition: all ease-in-out .5s; /* easy animation if you need it */
}
.button-size button:hover
{
width: calc(100% - 20px);
height: calc(100% - 3em);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sonali |
Solution 2 |