Dynamically calculate a div width
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">100000000000000开发者_如何学JAVA0000000000</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
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.
This can be done with calc
width: -webkit-calc(50% - 7px) !important;
width: -moz-calc(50% - 7px) !important;
width: calc(50% - 7px) !important;
More info and examples https://developer.mozilla.org/en-US/docs/Web/CSS/calc
Try this css for parent:
#parent {
overflow:auto; height:100px;
padding: 0 5px 0 5px;
}
That's what the selectors are for in CSS:
#parent.div {
width: 100%;
margin-left: 10px;
margin-right: 10px;
}
精彩评论