【问题标题】:How to scale element in pixel with CSS? [duplicate]如何使用 CSS 以像素为单位缩放元素? [复制]
【发布时间】:2022-04-22 15:15:19
【问题描述】:

可以使用transform: scale(sx) 缩放元素,其中sx 是(无单位的)缩放因子。有没有办法将元素缩小一定数量的像素(不知道它的宽度)。

编辑

我想在不同大小的元素(例如按钮)被按下时调整它们的大小。但是,在所有按钮上应用相同的比例因子,比如scale(.95),会导致较大(较小)的按钮被缩放太多(很小)。所以,我想做的是在绝对按下时调整所有元素的大小,即按一定数量的像素或 em 左右。

【问题讨论】:

  • 您需要问自己如何使用像素? scale(5px) 是什么意思?
  • 您可能的意思是调整大小,因为您在谈论固定单位或像素,否则不,不使用 CSS(但希望如此),如果 CSS vars 可以“接受”自动为有效/有意义的价值和“存储”它的暗淡。供以后使用,然后你可以做例如::root {--w: auto} div {width: var(--w)} div:hover {width: calc(var(--w) - 5px);
  • @VXp 谢谢。是的,我的意思是调整大小。你的意思不是“否则”而是“在那种情况下”,对吧?
  • 不是真的,一般来说,不仅仅是在你的情况下,CSS 不能做到这一点,现在......真可惜。
  • 这听起来像是一个 XY 问题。 IE。尝试缩放 -5px 是解决 original 问题的一部分。那么你能详细说明一下最初的问题是什么吗?

标签: css


【解决方案1】:

这就是您可以使用原生 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>

【讨论】:

    【解决方案2】:

    我知道的唯一方法(仅使用 css)是您执行以下操作:

    这只有在它的宽度和高度不依赖于元素内容时才有效

    1. 用代表默认大小的元素围绕要缩放的元素。这可以设置为像素或百分比或它选择的任何比例(如自动)
    2. :hover 上使用 css calc 函数执行 calc(100% - <number><em|rm|px|%>) 以按 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2020-12-27
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 2015-03-24
      相关资源
      最近更新 更多