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
<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');
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.
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.
See jQuery calculate padding-top as integer in px
Use the same logic as border or padding.
Alternatively, you could use outerWidth. The pseudo-code should bemargin = (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.
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
});
$('img').margin() or $('img').padding()
return:
{bottom: 10 ,left: 4 ,top: 0 ,right: 5}
get value:
$('img').margin().top
Edit:
use jquery plugin: jquery.sizes.js
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>'));
});