jQuery – Dimensions
The jQuery Dimensions methods include:
- .width() – Returns the current computed width of the first element in the matched set.
- .height() – Returns the current computed height of the first element in the matched set.
- .innerWidth() – Returns the current computed width of the first element in the matched set, including padding but not border.
- .innerHeight() – Returns the current computed height of the first element in the matched set, including padding but not border.
- .outerWidth() – Returns the current computed width of the first element in the matched set, including padding and border but not margin.
- .outerHeight() – Returns the current computed height of the first element in the matched set, including padding and border but not margin.
- .offset() – Returns an object containing the top and left coordinates of the first element in the matched set relative to the document.
- .position() – Returns an object containing the top and left coordinates of the first element in the matched set relative to its offset parent.
These methods can be useful for a wide range of tasks, including resizing and positioning elements, animating elements, and calculating the dimensions of elements for use in other functions or plugins.
<!DOCTYPE html> <html> <head> <title>jQuery Dimensions Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> #box { width: 200px; height: 150px; padding: 10px; border: 2px solid black; margin: 20px; } </style> </head> <body> <div id="box">This is a box</div> <script> $(document).ready(function() { // Get the width and height of the box var width = $("#box").width(); var height = $("#box").height(); console.log("Box width: " + width + "px, Box height: " + height + "px"); // Get the inner width and height of the box var innerWidth = $("#box").innerWidth(); var innerHeight = $("#box").innerHeight(); console.log("Box inner width: " + innerWidth + "px, Box inner height: " + innerHeight + "px"); // Get the outer width and height of the box var outerWidth = $("#box").outerWidth(); var outerHeight = $("#box").outerHeight(); console.log("Box outer width: " + outerWidth + "px, Box outer height: " + outerHeight + "px"); // Get the offset position of the box var offset = $("#box").offset(); console.log("Box offset position - Top: " + offset.top + "px, Left: " + offset.left + "px"); // Get the position of the box relative to its offset parent var position = $("#box").position(); console.log("Box position relative to its offset parent - Top: " + position.top + "px, Left: " + position.left + "px"); }); </script> </body> </html>