Scale element in X and Y by the same amount of pixels

Viewed 247

I'd like to scale an element by the same absolute amount of pixels (not the same ratio) in the X and Y direction such that

newWidth = oldWidth + n
newHeight = oldHeight + n

where n is the number of pixels gained in size and oldWidth and oldHeight are unknown.

Is there a way to do this in pure CSS?

2 Answers

You can use CSS variables like this:

CSS

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

More dynamic but not recommend:

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

AND...

: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);
}

If the dimensions are unknown, you can't use CSS. In this case, only JavaScript can do that.

To do that in JavaScript, first grab the dimension of the element, and then add or subtract a value dynamically.

Related