How do you find the current width of a <div>
in a cross-browser compatible way without using a library like jQuery?
auto automatically computes the width such that the total width of the div fits the parent, but setting 100% will force the content alone to 100%, meaning the padding etc. will stick out of the div, making it larger than the parent. so setting the 'width' to 'auto' would be better? Yes, but that's the default anyway.
To get the width of a specific HTML Element in pixels, using JavaScript, get reference to this HTML element, and read the clientWidth property of this HTML Element. clientWidth property returns the width of the HTML Element, in pixels, computed by adding CSS width and CSS padding (top, bottom) of this HTML Element.
document.getElementById("mydiv").offsetWidth
You can use clientWidth
or offsetWidth
Mozilla developer network reference
It would be like:
document.getElementById("yourDiv").clientWidth; // returns number, like 728
or with borders width :
document.getElementById("yourDiv").offsetWidth; // 728 + borders width
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With