Get correct margin, padding and sizes of elements

by Hugo Carneiro

HTML

<div>
  Hello
</div>

CSS

body {
  margin: 0;  
}

div {
  width: 50%;
  height: 100px;
  background: red;
  margin: auto 20px auto auto;
  padding: 20px;
  display: block;
}

JavaScript

function getValue(val) {
	return parseInt(val, 10)
}

function calculateComputedProperties(element) {
	const compStyles = element.currentStyle || window.getComputedStyle(element)
  const divRect = element.getBoundingClientRect()
  const parent = element.parentElement
  const parentRect = parent.getBoundingClientRect()
  
  // Margins
  const marginTop = compStyles.getPropertyValue('margin-top')
  let marginRight = compStyles.getPropertyValue('margin-right')
  const marginBottom = compStyles.getPropertyValue('margin-bottom')
  let marginLeft = compStyles.getPropertyValue('margin-left')
  
  const simpleMarginRight = getValue(marginRight)
  const simpleMarginLeft = getValue(marginLeft)
  
  // Paddings
  const paddingTop = compStyles.getPropertyValue('padding-top')
  const paddingRight = compStyles.getPropertyValue('padding-right')
  const paddingBottom = compStyles.getPropertyValue('padding-bottom')
  const paddingLeft = compStyles.getPropertyValue('padding-left')
  
  const simplePaddingTop = getValue(paddingTop)
  const simplePaddingRight = getValue(paddingRight)
  const simplePaddingBottom = getValue(paddingBottom)
  const simplePaddingLeft = getValue(paddingLeft)
  
  // Borders
  var borderTop = compStyles.getPropertyValue('border-top-width');
  
  // Sizes
  const width = `${divRect.width - simplePaddingLeft - simplePaddingRight}px`
  const height = `${divRect.height - simplePaddingTop - simplePaddingBottom}px`
  
  // Display
  const display = compStyles.getPropertyValue('display')

  if (display === 'block') {
    const margin = parentRect.width - divRect.width

    // Aligned right
    if (divRect.right - simpleMarginRight == parentRect.right) {
      marginLeft = `${margin}px`;
    } else if (divRect.left - simpleMarginLeft == parentRect.left) {
      // Aligned left
      marginRight = `${margin}px`;
    }
  }
  
  return {
  	display,
    width,
    height,
  	marginTop,
    marginRight,
    marginBottom,
    marginLeft,
    paddingTop,
   ...