Get Element CSS Property (Width/Height) Value as It Was Set (In Percent/Em/Px/Etc)

Get element CSS property (width/height) value as it was set (in percent/em/px/etc)

Good news everyone! There seems to be a CSS Typed OM on his way in the w3c drafts.

Fast reading this document, it seems that the goal of this maybe to-be specification, is to ease the access of CSSOM values from javascript.

The really important part of this for us here is that we will have a CSSUnitValue API, which will be able to parse CSS values to an object of the form

{
value: 100,
unit: "percent", // | "px" | "em" ...
type: "percent" // | "length"
}

And add a computedStyleMap() method, to the Element interface, from which we will be able to get the values actually applied on our elements.

As of today, only Chrome implements it (since 66).

(() => {  if (!Element.prototype.computedStyleMap) {    console.error("Your browser doesn't support CSS Typed OM");    return;  }  document.querySelectorAll('.test')    .forEach((elem) => {      let styleMap = elem.computedStyleMap();      const unitvalue = styleMap.get('width');      console.log(elem, {        type: unitvalue.type(),        unit: unitvalue.unit,        value: unitvalue.value      });    });
/* outputs
<div class="b test">first</div> { "type": { "length": 1 }, "unit": "px", "value": 100 } <div id="a" class="a test">second</div> { "type": { "percent": 1 }, "unit": "percent", "value": 50 }
*/
})();
div.test {  width: 100px; }x,div#a {  width: 50%; }.a {  width: 75%; }
<div class="b test">first</div><div id="a" class="a test">second</div>

How to get CSS height and width if they are in percentage value using JavaScript?

The height of an element a as a percentage of its parent can be calculated as

getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%'

This works however the styles of a and its parent have been set (through classes, through inline style setting). It is not the same as finding out whether the heights were set by a percentages or by other units initially.

Here's a simple example:

let a = document.querySelector(".field");

console.log(getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%');
.container {
height: 50vh;
width: 30vw;
}

.field {
height:50%;
width:25%;
}
<div class="container">
<div class="field"></div>
</div>

How can I get a CSS value in its original unit with javascript?

Just for fun - this is wildly inefficient, but you could parse each stylesheet, check if each rule matches the element, if it does, add the rule to a list of matches. Then, for each match, check if setting the inline style of that element to that rule changes the computed value, if it doesn't, assume that is the rule in use:

const getCssActualValue = (el, property) => {
const matches = new Set();
const allCSS = [...document.styleSheets]
.map(styleSheet => {
try {
return [...styleSheet.cssRules]
.map(rule => rule.cssText)
.join('');
} catch (e) {
console.log('Access to stylesheet %s is denied. Ignoring...', styleSheet.href);
}
})
.filter(Boolean)
.map(rule => rule.split('}'))
.forEach((styleSheet) => {
styleSheet.forEach((rule) => {
const [selector, styles] = rule.split(' {');
try {
if (selector && el.matches(selector)) {
styles.split(';').map(el => el.trim()).forEach((rule) => {
const [prop, val] = rule.split(': ')
if (prop === property) {
matches.add(val);
}
});
}
} catch {}
});
});
return Array.from(matches);
}


const getCurrentCssValue = (el, property) => {
const matches = getCssActualValue(el, property);
const current = getComputedStyle(el)[property];
const currentInline = el.style[property];
for (const match of matches) {
el.style[property] = match;
if (getComputedStyle(el)[property] === current) {
el.style[property] = currentInline;
console.log({match});
return match;
}
}
el.style[property] = currentInline;
return currentInline;
}

const property = 'height';
const el = document.getElementById('test');
el.innerText = getCurrentCssValue(el, property);
#test{
width:200px;
height:20vh;
background:LawnGreen;
}
<div id="test"></div>

How to get the inherited values of element from JavaScript

You can simply implement a pixel-to-rem converter and use that:

function convertPixelsToRem(pixels) {
return ((pixels.replace("px", "") / getComputedStyle(document.documentElement).fontSize.replace("px", "")) + "rem");
}

console.log(convertPixelsToRem(window.getDefaultComputedStyle(document.getElementById("new").querySelector(".h1"))["font-size"]));
<style>
#new {
font-size: 2rem;
}
</style>
<div id="new">
<h1 class="h1">This is a heading</h1>
<!–– Here h1 is inheriting font-size from div ––>
</div>

jQuery - find out the width of an element as specified in CSS (e.g. in %age if it was specified in %age, not just in px)

I couldn't find a way to do what I asked for in the question but I came up with a workaround which allows me to do what I need to in my situation. The code in question is for my jQuery plugin called jScrollPane ( http://jscrollpane.kelvinluck.com/ ). In the end what I do is set the width to null (elem.css('width', null);). This removes the width I had set myself previously and allows the element to take it's natural width as defined in the stylesheet (i.e. using a percentage if that's how it was defined). I can then measure this new value and use that to set the width to the number I desire...

Setting width/height as percentage minus pixels

You can use calc:

height: calc(100% - 18px);

Note that some old browsers don't support the CSS3 calc() function, so implementing the vendor-specific versions of the function may be required:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);


Related Topics



Leave a reply



Submit