jQuery get element padding/margin

Sam Deering
Share

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.

//sets
$("div.header").css("margin","10px");
$("div.header").css("padding","10px");

Common sense, you would think this would work, but doesn’t seem to.

//gets
$("div.header").css("margin");
$("div.header").css("padding");

Try it yourself (paste code below into Firebug). You’ll see empty values returned for margin and padding. Maybe I’m missing something here?

(function($){

function logMarginPadding(elem)
{
//gets
var margin = elem.css("margin"),
padding = elem.css("padding");
console.log("margin="+margin+" padding="+padding);
}

var elem = $("div.header"); //set the element to inspect

logMarginPadding(elem);
//sets
elem.css("margin","10px");
elem.css("padding","10px");
logMarginPadding(elem);

})(jQuery);

This seems to work.

//get top margin of element
alert($("div.header").css("margin-top"));

//get top margin of element as integer value
alert($("a").css("margin-top").replace("px", ""));

//if using it with a calculation you must convert it to an integer
parseInt($("a").css('padding-left').replace("px", ""));

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.

var item = $('div.header');
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.

JSizes is a small plugin for the jQuery JavaScript library which adds support for querying and setting the CSS min-width, min-height, max-width, max-height, border-*-width, margin, and padding properties.

Further readings
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
http://api.jquery.com/outerHeight/
http://api.jquery.com/outerWidth/