Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

Get content width of an element

offsetWidth isn't good enough for me right now, as this includes padding and border width. I want to find out the content width of the element. Is there a property for that, or do I have to take the offsetWidth and then subtract the padding and border width from the computed style?

Upvotes: 16

Views: 22971

Answers (4)

dbquarrel
dbquarrel

Reputation: 1446

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.

Upvotes: 0

Loilo
Loilo

Reputation: 14735

Since this comes up first when googling but doesn't have an appropriate answer yet, here's one:

function getContentWidth (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!

Upvotes: 18

founddrama
founddrama

Reputation: 2411

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;

Upvotes: 4

martineno
martineno

Reputation: 2635

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.

Upvotes: 2

Related Questions