Friday, January 4, 2013

How to calculate width of any element including padding, border and margin using jQuery?

To calculate width of any element including padding, border and margin we can make use of the ".outerWidth(true)" method of jQuery. This method will return width including left and right padding, border and margin.

Note: We cannot use this method to calculate width of window and document, instead we can use ".width()" method.

If the method ".outerWidth()" is used without passing Boolean parameter, it will return width including left and right padding and border.

1. How to calculate width of any element using jQuery?
2. How to calculate width of any element including padding using jQuery?
3. How to calculate width of any element including padding, border and margin using jQuery?(this article)

Calculate height of element using ".outerWidth()" method:

$(document).ready(function(){
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");
});

If the method ".outerWidth(true)" is used passing Boolean parameter "true", it will return width including left and right padding and border.

Calculate height of element using ".outerWidth(true)" method:

$(document).ready(function(){
$("div.outerWidthMargin").append($("div.outerWidthMargin").outerWidth(true)+" px");
});

Example:

<!DOCTYPE html>
<html>
<head>
<style> 
  div {margin:10px;padding:10px;border:3px solid #666;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("div.Width").append($("div.Width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");
$("div.outerWidthMargin").append($("div.outerWidthMargin").outerWidth(true)+" px");
});
</script>
</head>
<body>
<div class="Width">Width of this div container without including padding, border and margin is: </div>
<div class="innerWidth">Width of this div container including padding is: </div>
<div class="outerWidth">Width of this div container including padding and border is: </div>
<div class="outerWidthMargin">Width of this div container including padding, border and margin is: </div>
</body>
</html>

Sample output:


How to calculate width of any element including padding, border and margin using jQuery

Demo:



2 comments:

  1. Very Nice Tip, I was looking for a quickest way to calculate the width of objects. Thank you. It really gonna help me in my future projects.

    ReplyDelete

Subscribe via Email