For a div with css of {padding:10% 10px 20% 10px;} I need to be able to retrieve via JavaScript the padding as it is set but window.getComputedStyle(myelement).getPropertyValue('padding'); returns different results.
Firefox = "10% 10px 20% 10px"
Chromium = "59.8839px 10px 119.768px 2px"
Is there any other way to retrieve this info so it gets the % values and not the elements current state px value?
http://jsfiddle.net/o1jhbn9f/1/
var div = document.getElementsByTagName('div')[0];
console.log(window.getComputedStyle(div).getPropertyValue('padding'));
CodePudding user response:
Hi friend maybe this example could help you. In resume the function that i test get the topBottom and leftRight property style and use split to get each side and concatenate in the right way. I hope you can use it.
function getPaddingCSS(selector) {
const elementoApp = window.getComputedStyle(document.querySelector(selector), null);
const elementPadding = {
topBottom: elementoApp.paddingBlock,
topBottomList: elementoApp.paddingBlock.split(' '),
leftRight: elementoApp.paddingInline,
leftRightList: elementoApp.paddingInline.split(' ')
}
const paddingStr = `${elementPadding.topBottomList[0]} ${elementPadding.leftRightList[1]} ${elementPadding.topBottomList[1]} ${elementPadding.leftRightList[0]}`;
return paddingStr;
}
const selector = 'navbar';
const paddingCSS = getPaddingCSS(selector)
console.log('paddingStr of ' selector.toUpperCase() ':', paddingCSS)
.navbar{
padding: 3% 15px 30% 60px;
}
<navbar >
</navbar>