Search code examples
javascripthtmlcsswidth

How to set width of div to another div's width?


I'm trying to set, with javascript, the width of one div to the width of another. In my case, the second div was cloned from the first.

The issue I'm running into is related to padding, and how style.width is defined differently from clientWidth/offsetWidth/scrollWidth. In my example below, I have two divs defined the same except with different widths. When the button is pressed, I'm trying to set the width of the smaller one to the bigger one - but the outcome is that it gets the width of the bigger one PLUS the padding (an extra 20px).

Is there a way to change the line:

two.style.width = one.clientWidth + 'px';

to make the two divs equal in width?

function setWidth() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");
  two.style.width = one.clientWidth + 'px';
}
.outer {
  background: red;
  padding: 10px;
  } 
.inner {
  background: green;
  height: 10px;
  } 

#one {
  width: 100px; 
}
#two {
  width:50px;
    }
<div id=one class=outer><div class=inner></div></div>
<br>
<div id=two class=outer><div class=inner></div></div>
<button onclick="setWidth()">SET WIDTH</button>


Solution

  • You can use getComputedStyle:

    function setWidth() {
      var one = document.getElementById("one");
      var two = document.getElementById("two");
      style = window.getComputedStyle(one);
      wdt = style.getPropertyValue('width');
      two.style.width = wdt;
    }
    

    Here's a fiddle