Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert css margin value to pixels with just plain javascript?

I'm looking for the simplest and cross browser way to convert html element css margin value to absolute pixels. Say for instance the margin is "auto". I can't use any js framework.

like image 504
gztomas Avatar asked Nov 09 '12 13:11

gztomas


People also ask

How do you find margin value?

To calculate profit margin, start with your gross profit, which is the difference between revenue and COGS. Then, find the percentage of the revenue that is the gross profit. To find this, divide your gross profit by revenue. Multiply the total by 100 and voila—you have your margin percentage.


1 Answers

You want to use the window.getComputedStyle method:

var style = window.getComputedStyle(element, null);
// style.marginLeft

Here's a working demo: http://jsfiddle.net/VxccZ/

Update

For IE 8 and older (that do not support this method), use the currentStyle property of your element:

var style = element.currentStyle;
// style.marginLeft

To summarize:

var getMarginLeft = function (element) {
  var style;
  if (window.getComputedStyle) { style = window.getComputedStyle(element, null); }
  else { style = element.currentStyle; }

  return style.marginLeft;
};

I'm not 100% sure that currentStyle features a numeric value for margin: auto. You will have to try that yourself. I cannot do that myself on the Mac.

like image 152
J. K. Avatar answered Nov 09 '22 23:11

J. K.