Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically calculate a div width

Tags:

javascript

Here are sample divisions:

#grandparent {
  width: 100px;
}
#parent {
  overflow: auto;
  height: 100px;
}
.child {
  overflow: hidden;
  margin-left: 10px;
}
<div id="grandparent">

  <div id="parent">

    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>

  </div>

</div>

The <div class="child"> width value is always 10 pixels less than <div id="parent"> width value. How can it be calculated so any width value is given to <div id="parent">, its child gets 10 pixels less than that?

Any help is very much appreciated!

Mike

like image 380
Mori Avatar asked Feb 24 '23 09:02

Mori


1 Answers

With jQuery, this is very easy. Just subtract 10 from what.innerWidth() Here:

$(".child").css('width', $('#parent').innerWidth()-10);

You could also do it like this:

$(".child").each(function(){
    $(this).css('width', $(this).parent().innerWidth()-10);
});

-Which means you could have more than one parent, without having to know the id.

Normal JS

You can use the clientWidth property of an HTML element object. Like this:

var targetParent = document.getElementById('parent'); // or whatever
var targets = targetParent.getElementsByClassName('child');
for(var i=0;i<targets.length;i++) targets[i].parentNode.style.width = targets[i].clientWidth - 10;

Hope this helps! - Tanner.

like image 121
Tanner Ottinger Avatar answered Mar 12 '23 21:03

Tanner Ottinger