Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate element's width and height with their padding / margin values using less code?

I am using height() / width() method but its returning value without it's padding and margin values. I am not having problem to calculate total with / height values.

This way is working but my problem is; its too long to calculate all of them. Is there a way to calculate these with less code without bugs ?

Here is jsFiddle example.

jQuery:

var ele = $('div');

var eleW = ele.width();
var eleH = ele.height();

alert(eleW);//returning 200
alert(eleH);//returning 100

var eleMR = parseInt(ele.css('margin-right'));
var eleML = parseInt(ele.css('margin-left'));
var eleMT = parseInt(ele.css('margin-top'));
var eleMB = parseInt(ele.css('margin-bottom'));

var elePR = parseInt(ele.css('padding-right'));
var elePL = parseInt(ele.css('padding-left'));
var elePT = parseInt(ele.css('padding-top'));
var elePB = parseInt(ele.css('padding-bottom'));

var eleTotalWidth = eleMR + eleML + elePR + elePL + eleW;
var eleTotalHeight = eleMT + eleMB + elePT + elePB + eleW;

alert(eleTotalWidth);//returning 147
alert(eleTotalHeight);//returning 122

css:

div {
       float:left; width:100px; height:200px; background-color:#000;
       margin:5px 3px 2px 4px; padding:10px 20px 5px;
     }​
like image 946
Barlas Apaydin Avatar asked Jul 26 '12 08:07

Barlas Apaydin


People also ask

How do you find the height of an element with padding?

Using jQuery, you can get element height including padding with $(ele). outerHeight() , get element height including padding, border and margin by $(ele). outerHeight(true) .

Which method is used to find width of an element with padding and border?

If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the HTMLElement. offsetWidth and HTMLElement. offsetHeight properties.

How do you measure the width of a padding box?

Here the dimensions of the element are calculated as: width = border + padding + width of the content, and height = border + padding + height of the content.

How does the CALC () function work on values in CSS?

The calc() function takes a single expression as its parameter, with the expression's result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules: + Addition.


1 Answers

Use outerWidth(); and outerHeight();

var ele = $('div');

var eleW = ele.outerWidth(true);
var eleH = ele.outerHeight(true);
like image 89
Vins Avatar answered Oct 23 '22 18:10

Vins