121

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/

Tom
  • 1,229
  • 2
  • 8
  • 5
  • http://stackoverflow.com/questions/590602/padding-or-margin-value-in-pixels-as-integer-using-jquery – Artem Pianykh Sep 14 '11 at 17:35
  • Please refer to the below link which is some what similar. http://stackoverflow.com/questions/590602/padding-or-margin-value-in-pixels-as-integer-using-jquery – Praveen Sep 14 '11 at 17:36

8 Answers8

215
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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Dan Short
  • 9,598
  • 2
  • 28
  • 53
  • 1
    If that's the case, you can take the values calculated, append 'px' and you've got the pixel values. – Dan Short Sep 14 '11 at 17:38
  • Updated answer and jsFiddle with results. – Dan Short Sep 14 '11 at 17:45
  • thanks a heap however I'm looking for the printed values so I can reapply them ? i.e. 30px 30px 30px 30px or 30px 5px 15px 30px etc – Tom Sep 14 '11 at 17:51
  • 2
    You need to update your question to make that clear then. Otherwise we're wasting time writing solutions to problems you're not trying to solve :). Explain in your question exactly the return values you want. You asked for _total_ margin and padding of the element, not the individual margin values (which may be different for `margin-left` and `margin-right`, and may be `em` or `px`. – Dan Short Sep 14 '11 at 17:53
  • sorry, i thought `elements formatted total padding and margin` was clear. will clarify – Tom Sep 14 '11 at 17:55
  • 2
    It is, but that was my edit to your question, not your original question :) – Dan Short Sep 14 '11 at 18:03
  • ok i just lol'd at your comment :D sorry for taking credit for your edit to my post :) – Tom Sep 14 '11 at 18:11
  • 4
    This is very useful; what to do if the left and right margin/padding values are different and you want, for example, just the left margin or padding value? – jpap May 24 '13 at 20:33
  • 1
    Isn't top margin connected to the `height` not the `width`? – JohnK Nov 14 '13 at 16:39
  • Yes, I was just using the OPs variable names. You would have to calculate the top/bottom margin, border, and padding separately. – Dan Short Nov 15 '13 at 01:04
  • No way to retreive different values for left/right and top/bottom by this approach. The accepted one by Elias Zamaria achieves that. Don't be blindly fooled by the high rate, think to what you all actually need. – Niki Romagnoli Feb 01 '17 at 10:15
117

According to the jQuery documentation, shorthand CSS properties are not supported.

Depending on what you mean by "total padding", you may be able to do something like this:

var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');
Dan Short
  • 9,598
  • 2
  • 28
  • 53
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
  • 28
    Don't pull it out like this. What if one is `auto` or `2%` or `inherit`? – Lightness Races in Orbit Sep 14 '11 at 18:01
  • @Dan - really appreciate the effort Dan. apologies for not clarifying more :( Sorry to waste your time. – Tom Sep 14 '11 at 18:07
  • It happens :). Writing good questions is almost as hard as writing good answers. – Dan Short Sep 14 '11 at 18:12
  • 3
    You are right about non-numeric values. I think Dan Short's answer is more robust. – Elias Zamaria Sep 14 '11 at 18:37
  • 4
    [update](http://api.jquery.com/css/) : As of jQuery 1.9, passing an array of style properties to .css() will result in an object of property-value pairs. For example, to retrieve all four rendered border-width values, you could use `$( elem ).css([ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth" ]).` – Hussein Nazzal Mar 05 '14 at 02:07
  • This answer really falls apart if you happen to want the _current, numeric_ value of those things. – aroth Nov 04 '14 at 13:37
  • @LightnessRacesinOrbit while you are technically right the thought of someone using percent based padding makes me want to slap the person who came up with it – Dbl Jul 06 '15 at 14:21
19

jQuery.css() returns sizes in pixels, even if the CSS itself specifies them in em, or as a percentage, or whatever. It appends the units ('px'), but you can nevertheless use parseInt() to convert them to integers (or parseFloat(), for where fractions of pixels make sense).

http://jsfiddle.net/BXnXJ/

    $(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});
Michael Scheper
  • 6,514
  • 7
  • 63
  • 76
RavenHursT
  • 2,336
  • 1
  • 25
  • 46
4

This works for me:

var tP = $("img").css("padding").split(" ");
var Padding = {
    Top: tP[0] != null ? parseInt(tP[0]) : 0,
    Right: tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0),
    Bottom: tP[2] != null ? parseInt(tP[2]) : (tP[0] != null ? parseInt(tP[0]) : 0),
    Left: tP[3] != null ? parseInt(tP[3]) : (tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0))
};

Result example:

Object {Top: 5, Right: 8, Bottom: 5, Left: 8}

To make a total:

var TotalPadding = Padding.Top + Padding.Right + Padding.Bottom + Padding.Left;
Brutus
  • 41
  • 6
3

Border

I believe you can get the border width using .css('border-left-width'). You can also fetch top, right, and bottom and compare them to find the max value. The key here is that you have to specify a specific side.

Padding

See jQuery calculate padding-top as integer in px

Margin

Use the same logic as border or padding.

Alternatively, you could use outerWidth. The pseudo-code should be
margin = (outerWidth(true) - outerWidth(false)) / 2. Note that this only works for finding the margin horizontally. To find the margin vertically, you would need to use outerHeight.

Community
  • 1
  • 1
simshaun
  • 21,263
  • 1
  • 57
  • 73
  • Your strategy for margin doesn't work in Firefox, it will return 0 every time if you have "auto" horizontal padding, for example to center the element. – Ben Dilts Aug 22 '14 at 16:18
2

I've a snippet that shows, how to get the spacings of elements with jQuery:

/* messing vertical spaces of block level elements with jQuery in pixels */

console.clear();

var jObj = $('selector');

for(var i = 0, l = jObj.length; i < l; i++) {
  //jObj.eq(i).css('display', 'block');
  console.log('jQuery object:', jObj.eq(i));
  console.log('plain element:', jObj[i]);

  console.log('without spacings                - jObj.eq(i).height():         ', jObj.eq(i).height());
  console.log('with padding                    - jObj[i].clientHeight:        ', jObj[i].clientHeight);
  console.log('with padding and border         - jObj.eq(i).outerHeight():    ', jObj.eq(i).outerHeight());
  console.log('with padding, border and margin - jObj.eq(i).outerHeight(true):', jObj.eq(i).outerHeight(true));
  console.log('total vertical spacing:                                        ', jObj.eq(i).outerHeight(true) - jObj.eq(i).height());
}
Andreas
  • 65
  • 6
0

If the element you're analyzing does not have any margin, border or whatsoever defined you won't be able to return it. At tops you'll be able to get 'auto' which is normally the default.

From your example I can see that you have margT as variable. Not sure if're trying to get margin-top. If that's the case you should be using .css('margin-top').

You're also trying to get the stylization from 'img' which will result (if you have more than one) in an array.

What you should do is use the .each() jquery method.

For example:

jQuery('img').each(function() {
    // get margin top
    var margT = jQuery(this).css('margin-top');

    // Do something with margT
});
Community
  • 1
  • 1
José P. Airosa
  • 368
  • 1
  • 2
  • 11
-3

Edit:

use jquery plugin: jquery.sizes.js

$('img').margin() or $('img').padding()

return:

{bottom: 10 ,left: 4 ,top: 0 ,right: 5}

get value:

$('img').margin().top
WantToDo
  • 401
  • 1
  • 5
  • 11