jQuery How to Get Element's Margin and Padding?

Tom picture Tom · Sep 14, 2011 · Viewed 234.2k times · Source

Just wondering - how using jQuery - I can get an elements formatted total padding and margin etc ? i.e. 30px 30px 30px 30px or 30px 5px 15px 30px etc

I tried

var margT = jQuery('img').css('margin');
var bordT = jQuery('img').css('border');
var paddT = jQuery('img').css('padding');

But this doesn't work ? http://jsfiddle.net/q7Mra/

Answer

Dan Short picture Dan Short · Sep 14, 2011
var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();

var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';

Check the jQuery API docs for information on each:

Here's the edited jsFiddle showing the result.

You can perform the same type of operations for the Height to get its margin, border, and padding.