Jarolin V
Jarolin V

Reputation: 69

Calculate desired height of scaled down element

I'm using CSS transform: scale(0.6) to scale down a div. When the element is scaled down, it maintains its aspect ratio. However, in my case, this element needs to always have a height that will reach the bottom of the viewport. This means I need to adjust the height of the element while keeping its width and top position the same.

How do I calculate the height I need to apply so that the element reaches the bottom of the viewport exactly when transform: scale(x) is applied?

document.body.addEventListener('click', () => {
  document.querySelectorAll('div')[0].style.transform = 'scale(0.44)';
});
body {
  margin: 0;
  padding: 0;
  height: 100vh;
}

div {
  width: 350px;
  height: 100%;
  position: absolute;
  top: 0px;
  background-color: red;
  position: absolute;
  transform-origin: top;
}
<div><h1>TEST</h1></div>

Upvotes: 0

Views: 557

Answers (1)

A Haworth
A Haworth

Reputation: 36426

Your snippet works if you replace scale(n) with scaleX(n)

document.body.addEventListener('click', () => {
  document.querySelectorAll('div')[0].style.transform = 'scaleX(0.44)';
});
body {
  margin: 0;
  padding: 0;
  height: 100vh;
}

div {
  width: 350px;
  height: 100%;
  position: absolute;
  top: 0px;
  background-color: red;
  position: absolute;
  transform-origin: top;
}
<div></div>

Are you looking for a solution to a more general case?

Upvotes: 1

Related Questions