-1

Is there a way to know the actual length of div below after filling with text? with css (preferred) or javascript.

*{
  margin:0;
  padding:0;
}

div{
  display:inline-block;
  background-color:steelblue;
  font-family: roboto;
}
<div>what is my length?</div><br/>
<div>what is my length then????</div>
william007
  • 17,375
  • 25
  • 118
  • 194
  • Length as in width in pixels, or length as in number of characters? – yaakov May 10 '22 at 07:11
  • https://stackoverflow.com/questions/4680785/getting-width-of-a-div-element, https://stackoverflow.com/questions/16471767/get-div-width-and-height-in-javascript, https://stackoverflow.com/questions/4787527/how-to-find-the-width-of-a-div-using-vanilla-javascript, https://stackoverflow.com/questions/15945877/get-the-width-of-a-div-when-width-set-by-css-class, ... – Don't Panic May 10 '22 at 07:28

1 Answers1

1

In JS, you can use offsetWidth. You also have offsetHeight for the height.

console.log(document.getElementById("a").offsetWidth);
console.log(document.getElementById("b").offsetWidth);
*{
  margin:0;
  padding:0;
}

div{
  display:inline-block;
  background-color:steelblue;
}
<div id="a">what is my length?</div><br/>
<div id="b">what is my length then????</div>
Cédric
  • 2,239
  • 3
  • 10
  • 28