![](/img/trans.png)
[英]How to dynamically calculate the and restrict the width of a scrollable overflow div?
[英]Dynamically calculate a div width
以下是示例分区:
#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>
<div class="child">
宽度值始终比<div id="parent">
宽度值小 10 个像素。 如何计算它,以便将任何宽度值赋予<div id="parent">
,它的孩子得到的比这少 10 个像素?
很感谢任何形式的帮助!
麦克风
使用 jQuery,这很容易。 只需从what.innerWidth()
中减去 10 即可:
$(".child").css('width', $('#parent').innerWidth()-10);
你也可以这样做:
$(".child").each(function(){
$(this).css('width', $(this).parent().innerWidth()-10);
});
-这意味着您可以拥有多个父母,而不必知道id
。
您可以使用 HTML 元素 object 的clientWidth
属性。 像这样:
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;
希望这可以帮助。 - 坦纳。
试试这个 css 作为父母:
#parent {
overflow:auto; height:100px;
padding: 0 5px 0 5px;
}
这就是 CSS 中选择器的用途:
#parent.div {
width: 100%;
margin-left: 10px;
margin-right: 10px;
}
这可以用 calc 来完成
width: -webkit-calc(50% - 7px) !important;
width: -moz-calc(50% - 7px) !important;
width: calc(50% - 7px) !important;
更多信息和示例https://developer.mozilla.org/en-US/docs/Web/CSS/calc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.