Today I was looking at how to get and set padding/margin values for DOM elements. I’m looking more into the specific location of the outer margins and paddings. As you may know, it’s possible to set an elements padding and margin using CSS, but getting the correct values can be problematic.
Common sense, you would think this would work, but doesn’t seem to.
Try it yourself (paste code below into Firebug). You’ll see empty values returned for margin and padding. Maybe I’m missing something here?
var margin = elem.css("margin"),
padding = elem.css("padding");
var elem = $("div.header"); //set the element to inspect
This seems to work.
//get top margin of element as integer value
//if using it with a calculation you must convert it to an integer
Anyways, this is how I got the padding for the element. Not ideal and only works if the padding is uniform (same on each side) Simply get the width and outer width divided by 2.
width = item.width(),
padding = (item.outerWidth()-width)/2;
There is pretty popular plugin called jsizes which may a good solution to getting/setting margin/padding values on elements.
jQuery has the funtions outerWidth and outerHeight which include the border and padding by default, and also the margin if the first argument of the function is true