首页 > 解决方案 > 将 X 和 Y 中的元素缩放相同数量的像素

问题描述

我想在 X 和 Y 方向上以相同的像素绝对数量(不是相同的比率)来缩放一个元素,这样

newWidth = oldWidth + n
newHeight = oldHeight + n

其中n是大小增加的像素数,oldWidth并且oldHeight是未知的。

有没有办法在纯 CSS 中做到这一点?

标签: csscss-transforms

解决方案


您可以像这样使用 CSS 变量:

CSS

:root {
    --n: 100px
}
.sample {
    width: calc(300px + var(--n));
    height: calc(200px + var(--n));
}

更动态但不推荐:

:root {
    --n: 100px;
    --width: 100px;
    --height: 100px;
}
.sample {
    width: calc(var(--width) + var(--n));
    height: calc(var(--height) + var(--n));
}

和...

:root {
    --n: 100px;
    --width: 100px;
    --height: 100px;
    --new-width: calc(var(--n) + var(--width));
    --new-height: calc(var(--n) + var(--height));
}
.sample {
    width: var(--new-width);
    height: var(--new-height);
}

推荐阅读