Get Content Width Of An Element
Solution 1:
Since this comes up first when googling but doesn't have an appropriate answer yet, here's one:
functiongetContentWidth (element) {
var styles = getComputedStyle(element)
return element.clientWidth
- parseFloat(styles.paddingLeft)
- parseFloat(styles.paddingRight)
}
Basically, we first get the element's width including the padding (clientWidth
) and then substract the padding left and right. We need to parseFloat
the paddings because they come as px
-suffixed strings.
I've created a little playground for this on CodePen, check it out!
Solution 2:
I would suggest either scrollWidth
or the clientWidth
depending on whether you want to account for the scrollbar.
Check out Determining the dimensions of elements or the specification itself.
Solution 3:
It sounds to me like you want to use getComputedStyle
on the element. You can see an example of getComputedStyle
vs. offsetWidth
here: http://jsbin.com/avedut/2/edit
Or:
window.getComputedStyle(document.getElementById('your-element')).width;
Solution 4:
I have the similar issue where my parent element isn't the window or document... I am loading an image by Javascript and want it to center after loading.
var parent = document.getElementById('yourparentid');
var image = document.getElementById('yourimageid');
image.addEventListener('load'),function() {
parent.scrollBy((image.width-parent.clientWidth)/2,(image.height-parent.clientHeight)/2);
}
Whenever you set the src then it will scroll to the center of the image. This for me is in the context of zooming into a high res version of the image.
Post a Comment for "Get Content Width Of An Element"