How to get css element width property

I would like to get in my JS code the “original” CSS width property applied to the element, and not the runtime width (calculated).
eg.

.foo {
  width: 50% /* or 123px, or 5em, ...*/
}

in this case, I want to get "50%", not the px value computed at runtime. If the value is given in em, I want to get em as the result. window.getComputedStyle(foo, null).getPropertyValue('width'), returns the pixel value (at least on google chrome).
Actually, I need the text value of the CSS rule applied to the element.

+4
source share
1 answer

foo.width in pixels / parentElement.width * 100 = foo.width in % therefore in JS for example:

var width = document.getElementById('foo').offsetWidth;
var parentWidth = document.getElementById('parentOfFoo').offsetWidth;

var fooWidthPercentage = width / parentWidth * 100;
console.log(fooWidthPercentage);
0
source

Source: https://habr.com/ru/post/1655452/


All Articles