Element Width and Height
width()
Called with no argument, .width() returns just the element's inner content width, excluding any padding, border, or margin. Pass a number or CSS value to it instead, and it sets that content width directly.
Example: width()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:200px;padding:20px">Box</div>
<script>
console.log($("#box").width());
</script>
</body>
</html>
height()
height() gets or sets the content height of an element the same way width() handles width, ignoring padding, border, and margin in both directions. Together, the two give you precise control over an element's content box size.
Example: height()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="height:100px;padding:20px">Box</div>
<script>
console.log($("#box").height());
</script>
</body>
</html>
Changing Width and Height
Width and height can be changed together for simple resizing, such as scaling an image container to a new size in response to user input. Setting both at once keeps the element's proportions consistent with a design you're targeting.
Example: Changing Width and Height
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:100px;height:100px">Box</div>
<script>
$("#box").width(200).height(200);
</script>
</body>
</html>
Using Percentage Values
Width can be set using percentage strings like '50%' when the layout needs to be responsive to its parent's size rather than a fixed pixel value. jQuery computes the actual pixel width from that percentage but still returns pixel values when you read it back.
Example: Using Percentage Values
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:50%">Box</div>
<script>
$("#box").width("50%");
console.log($("#box").width());
</script>
</body>
</html>
Reading Dimensions
Reading dimensions is useful when you need to make layout decisions in JavaScript, such as deciding whether an element is wide enough to fit a tooltip beside it. Since these methods return live values, they always reflect the element's current rendered size.
Example: Reading Dimensions
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:150px">Box</div>
<script>
if ($("#box").width() > 100) {
console.log("Wide enough for a tooltip");
}
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: