Javascript DOM HTML Element clientWidth Property

Introduction

The clientWidth property returns the viewable width of an element in pixels, including padding, but not the border, scrollbar or margin.

Get the height and width of a <div> element, including padding:

Click the button to get the height and width of div, including padding (using both clientHeight and clientWidth).

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {// w  ww .  j a va2  s . c o m
  height: 250px;
  width: 400px;
  padding: 10px;
  margin: 15px;
  border: 5px solid red;
  background-color: lightblue;
}
</style>
</head>
<body>
<button onclick="myFunction()">Test</button>

<div id="myDIV">
  <b>Information about this div:</b><br>
  Height: 250px<br>
  Width: 400px<br>
  padding: 10px<br>
  margin: 15px<br>
  border: 5px<br>
  <p id="demo"></p>
</div>

<script>
function myFunction() {
  var elmnt = document.getElementById("myDIV");
  var txt = "Height including padding: " + elmnt.clientHeight + "px<br>";
  txt += "Width including padding: " + elmnt.clientWidth + "px";
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

If the element's content is wider than the actual width of the element, this property will only return the width that is visible.

Use the offsetHeight and offsetWidth properties to return the viewable height and width of an element, including padding, border and scrollbar.

To add scrollbar to an element, use the CSS overflow property.

This property is read-only.

The clientWidth property returns a Number representing the viewable width of an element in pixels, including padding.




PreviousNext

Related