-1

How to make width equaled to height into CSS rule using pure JS? May be, there is a solution in CSS.

CSS

#animation-2 > div.line {
  height: 10%;
  background: red;
}

JS

let line = document.querySelector('.line');
let height = line.offsetHeight;
document.querySelector('.line').style.width = height;

It doesn't work. I want value in pixels. May I forget to add something?

THanks

olezya
  • 33
  • 4
  • Length values in CSS always need a unit (unless the value is 0 to begin with.) – CBroe Aug 29 '22 at 08:18
  • 3
    _"May be, there is a solution in CSS."_ - https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio – CBroe Aug 29 '22 at 08:19

3 Answers3

2

You forgot the "px" suffix:

let line = document.querySelector('.line');
let height = line.offsetHeight;
document.querySelector('.line').style.width = height + 'px';

https://jsfiddle.net/yr5eu2gn/

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
0

The value stored in line.offsetHeight is a number counting pixels, while elem.style.width expects a string with unit.

Thus, you must write

document.querySelector('.line').style.width = height + 'px';
Jordan Breton
  • 1,167
  • 10
  • 17
0

offsetHeight does not get the size in percentage. It gets it in pixels. So, you need to get the parent height as well to figure out the size in percentage.

Also, you need to add what unit you want to use as well as Javascript only saves the number.

EDIT: Well... just saw your edit that you want it in pixels and not in percentage. Hope this helps someone.

let line = document.querySelector('.line');
let height = line.offsetHeight;
let parentHeight = line.offsetParent.offsetHeight;
let percentHeight = Math.round(100 * height / parentHeight);
line.style.width = percentHeight+"%";
line.innerHTML = percentHeight;
#animation-2{
height: 100vh;
}

#animation-2 > div.line {
  height: 10%;
  background: red;
}
<div id="animation-2">
<div class="line"></div>
</div>
Lisa
  • 323
  • 3
  • 14