0

Is there a way to get the entire width of a div including margins without using JQuery?

 div.outerWidth 

doesn't seem to work and clientWidth excludes margins.

user3219182
  • 69
  • 2
  • 10
  • jQuery has a lot of built in syntax-sugar that deals with the differences between web browsers, especially in the way that each browser handles its box-model. However, some more searching around here might have revealed this: http://stackoverflow.com/questions/4787527/how-to-find-the-width-of-a-div – Jason M. Batchelor Jan 29 '14 at 15:40
  • offsetWidth does not include margins – user3219182 Jan 29 '14 at 15:50
  • It's important to remember that jQuery is built on top of JavaScript. That is to say, anything jQuery can do, JavaScript can do. – George Jan 29 '14 at 16:06

2 Answers2

0

As far as I recall, there is no single property value to get this.

Basically you need to get the margin width (left and right) and add them to your existing dimensions. Additionally, unless you are using box-sizing (By default you are not) you will need to add padding left and right as well.

You can use getComputedStyle to get the actual values you require. For example:

window.getComputedStyle(element, null).getPropertyValue("margin-left");

Edit: I forgot border :P.... left and right border width as well...

major-mann
  • 2,602
  • 22
  • 37
0

Please have a look below code, there is being alert total width of div 220 including margin.

<style>
    #myDiv{
        width:200px;
        height:200px;
        margin:10px;
    }
</style>
<div id='myDiv'>
</div>
<script>
    var div = document.getElementById('myDiv');
    var style = window.getComputedStyle(div);
    var leftMargin = parseInt(style.marginLeft.match(/\d+/));
    var rightMargin = parseInt(style.marginRight.match(/\d+/));
    alert(div.clientWidth + leftMargin + rightMargin);
</script>
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34