Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
What is difference between innerWidth and outerWidth in jQuery?
innerWidth in jQuery
The innerWidth() method returns the inner width of the first matched element. It includes padding, but excludes border and margin. This method is useful when you need to calculate the content area plus padding of an element.
Example
You can try to run the following code to get the inner width in jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Inner Width of div element: " + $("div").innerWidth());
});
});
</script>
</head>
<body>
<div style="height:200px;width:500px;padding:20px;margin:10px;border:5px solid red; background-color:gray;"></div><br>
<button>Get Inner Width of div</button>
</body>
</html>
The output of the above code is ?
Inner Width of div element: 540
outerWidth in jQuery
The outerWidth() method returns the outer width of the first matched element. It includes padding and border, but excludes margin by default. You can optionally include margin by passing true as a parameter: outerWidth(true).
Example
You can try to run the following code to get the outer width in jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Outer Width of div element: " + $("div").outerWidth());
});
});
</script>
</head>
<body>
<div style="height:200px;width:500px;padding:20px;margin:10px;border:5px solid red; background-color:gray;"></div><br>
<button>Get Outer Width of div</button>
</body>
</html>
The output of the above code is ?
Outer Width of div element: 550
Key Differences
innerWidth(): Width + Padding = 500px + 40px = 540px
outerWidth(): Width + Padding + Border = 500px + 40px + 10px = 550px
outerWidth(true): Width + Padding + Border + Margin = 500px + 40px + 10px + 20px = 570px
Conclusion
The main difference is that innerWidth() includes only padding with the content width, while outerWidth() includes padding and border, making it larger than the inner width measurement.
