Padding or margin value in pixels as integer using jQuery

JavascriptJqueryCss

Javascript Problem Overview


jQuery has height() en width() functions that returns the height or width in pixels as integer...

How can I get a padding or margin value of an element in pixels and as integer using jQuery?

My first idea was to do the following:

var padding = parseInt(jQuery("myId").css("padding-top"));

But if padding is given in ems for example, how can I get the value in pixels?


Looking into the JSizes plugin suggested by Chris Pebble i realized that my own version was the right one :). jQuery returns always value in pixels, so just parsing it to integer was the solution.

Thanks to Chris Pebble and Ian Robinson

Javascript Solutions


Solution 1 - Javascript

You should be able to use CSS (http://docs.jquery.com/CSS/css#name). You may have to be more specific such as "padding-left" or "margin-top".

Example:

CSS

a, a:link, a:hover, a:visited, a:active {color:black;margin-top:10px;text-decoration: none;}

JS

$("a").css("margin-top");

The result is 10px.

If you want to get the integer value, you can do the following:

parseInt($("a").css("margin-top"))

Solution 2 - Javascript

Compare outer and inner height/widths to get the total margin and padding:

var that = $("#myId");
alert(that.outerHeight(true) - that.innerHeight());

Solution 3 - Javascript

The parseInt function has a "radix" parameter which defines the numeral system used on the conversion, so calling parseInt(jQuery('#something').css('margin-left'), 10); returns the left margin as an Integer.

This is what JSizes use.

Solution 4 - Javascript

PLEASE don't go loading another library just to do something that's already natively available!

jQuery's .css() converts %'s and em's to their pixel equivalent to begin with, and parseInt() will remove the 'px' from the end of the returned string and convert it to an integer:

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>'));
});

Solution 5 - Javascript

Here's how you can get the surrounding dimentions:

var elem = $('#myId');

var marginTopBottom  = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight  = elem.outerWidth(true)  - elem.outerWidth();

var borderTopBottom  = elem.outerHeight() - elem.innerHeight();
var borderLeftRight  = elem.outerWidth()  - elem.innerWidth();

var paddingTopBottom  = elem.innerHeight() - elem.height();
var paddingLeftRight  = elem.innerWidth()  - elem.width();

Pay attention that each variable, paddingTopBottom for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)

Solution 6 - Javascript

You can just grab them as with any CSS attribute:

alert($("#mybox").css("padding-right"));
alert($("#mybox").css("margin-bottom"));

You can set them with a second attribute in the css method:

$("#mybox").css("padding-right", "20px");

EDIT: If you need just the pixel value, use parseInt(val, 10):

parseInt($("#mybox").css("padding-right", "20px"), 10);

Solution 7 - Javascript

This simple function will do it:

$.fn.pixels = function(property) {
    return parseInt(this.css(property).slice(0,-2));
};

Usage:

var padding = $('#myId').pixels('paddingTop');

Solution 8 - Javascript

Parse int

parseInt(canvas.css("margin-left")); 

returns 0 for 0px

Solution 9 - Javascript

ok just to answer the original question:

you can get the padding as a usable integer like this:

> var padding = > parseInt($("myId").css("padding-top").replace("ems",""));

If you have defined another measurement like px just replace "ems" with "px". parseInt interprets the stringpart as a wrong value so its important to replace it with ... nothing.

Solution 10 - Javascript

You could also extend the jquery framework yourself with something like:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

$("#myObject").margin().top

Solution 11 - Javascript

Don't use string.replace("px", ""));

Use parseInt or parseFloat!

Solution 12 - Javascript

I probably use github.com/bramstein/jsizes jquery plugin for paddings and margins in very comfortable way, Thanks...

Solution 13 - Javascript

Shamelessly adopted from Quickredfox.

jQuersy.fn.cssNum = function(){
    return parseInt(jQuery.fn.css.apply(this, arguments), 10);
};

update

Changed to parseInt(val, 10) since it is faster than parseFloat.

http://jsperf.com/number-vs-plus-vs-toint-vs-tofloat/20

Solution 14 - Javascript

Not to necro but I made this which can determine pixels based on a variety of values:

$.fn.extend({
  pixels: function (property, base) {
    var value = $(this).css(property);
    var original = value;
    var outer = property.indexOf('left') != -1 || property.indexOf('right') != -1 
      ? $(this).parent().outerWidth()
      : $(this).parent().outerHeight();

    // EM Conversion Factor
    base = base || 16;
    
    if (value == 'auto' || value == 'inherit') 
        return outer || 0;
    
    value = value.replace('rem', '');
    value = value.replace('em', '');
    
    if (value !== original) {
       value = parseFloat(value);
       return value ? base * value : 0;
    }
     
    value = value.replace('pt', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? value * 1.333333 : 0; // 1pt = 1.333px
    }

    value = value.replace('%', '');

    if (value !== original) {
      value = parseFloat(value);
      return value ? (outer * value / 100) : 0;
    }

    value = value.replace('px', '');
    return parseFloat(value) || 0;
  }
});

This way, we take into account for sizing, and auto / inherit.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMalik AmurlayevView Question on Stackoverflow
Solution 1 - JavascriptIan RobinsonView Answer on Stackoverflow
Solution 2 - JavascriptSvante SvensonView Answer on Stackoverflow
Solution 3 - JavascriptguigouzView Answer on Stackoverflow
Solution 4 - JavascriptRavenHursTView Answer on Stackoverflow
Solution 5 - JavascriptFireAphisView Answer on Stackoverflow
Solution 6 - JavascriptRob GrantView Answer on Stackoverflow
Solution 7 - JavascriptmpenView Answer on Stackoverflow
Solution 8 - Javascripta53-416View Answer on Stackoverflow
Solution 9 - JavascriptEeKayView Answer on Stackoverflow
Solution 10 - JavascriptcralexnsView Answer on Stackoverflow
Solution 11 - JavascriptRubbelDeCatcView Answer on Stackoverflow
Solution 12 - JavascriptMustafahView Answer on Stackoverflow
Solution 13 - JavascriptyckartView Answer on Stackoverflow
Solution 14 - JavascriptNijikokunView Answer on Stackoverflow