这个小提琴是这个问题的结果。在其中,我有一个 3 div flexbox 和一个 4 div flexbox。(此时与Angular无关)
理想情况下,flex div 可以放在它们的容器内,但即使它们总体上比容器窄,它们也不适合(一个 div 被推出)。更令人困惑的是,它们的数量不同。
当有 4 个 div 时,4 个的宽度之和为 814px,而容器为 819px 宽。如果我将最宽 div 的宽度缩小 9 个像素,使总宽度为 804,它们都可以按预期放入容器中。
#hbox1: width is 819, inner is 819, outer is 821
0 Object {borderWidth: 0, marginWidth: 0, paddingWidth: 0, flex: 1,
1 Object {borderWidth: 2, marginWidth: 0, paddingWidth: 0, flex: 2,
2 Object {borderWidth: 0, marginWidth: 0, paddingWidth: 0, flex: 1,
3 Object {borderWidth: 0, marginWidth: 0, paddingWidth: 0, flex: 1,
#hbox1 finalFlexTotal is 814
当有 3 个 div 时,我必须将最宽 div 的宽度缩小 6 个像素,以使它们都适合它们的容器。
#hbox2: width is 819, inner is 819, outer is 821
0 Object {borderWidth: 0, marginWidth: 0, paddingWidth: 0, flex: 1,
1 Object {borderWidth: 2, marginWidth: 0, paddingWidth: 0, flex: 2,
2 Object {borderWidth: 0, marginWidth: 0, paddingWidth: 0, flex: 1,
#hbox2 finalFlexTotal is 815
我已经考虑了borderWidth,marginWidth 和paddingWidth 为0。为什么如果没有某种随机调整,div 不适合它们的容器?
这是小提琴消失的代码和html:
<html>
<body>
<div id="hbox1" style="border: 1px solid red">
<div flex=1 style="display:inline-block;height:100%">This is the A Box</div>
<div flex=2 style="border:1px solid black;display:inline-block;height:100%">This is the B Box</div>
<div flex=1 style="display:inline-block;height:100%">This is the C Box</div>
<div flex=1 style="display:inline-block;height:100%">This is the D Box</div>
</div>
<div id="hbox2" style="border: 1px solid red;margin-top:40px">
<div flex=1 style="display:inline-block;height:100%">This is the A Box</div>
<div flex=2 style="border:1px solid black;display:inline-block;height:100%">This is the B Box</div>
<div flex=1 style="display:inline-block;height:100%">This is the C Box</div>
</div><script type="text/javascript" src="jquery-1.10.2.js" />
<script type="text/javascript">
function flexBoxIt(selector) {
var $node,
index,
flexValue,
flexInfo = [],
totalFlex = 0,
finalFlexTotal = 0;
$(selector).children('div').each(function (index) {
$node = $(this);
flexValue = $node.attr("flex");
flexValue = flexValue ? parseInt(flexValue, 10) : 1,
flexInfo[index] = {
"borderWidth": parseInt($node.css('borderLeftWidth'), 10) + parseInt($node.css('borderRightWidth'), 10),
"marginWidth": parseInt($node.css('marginLeft'), 10) + parseInt($node.css('marginRight'), 10),
"paddingWidth": parseInt($node.css('paddingLeft'), 10) + parseInt($node.css('paddingRight'), 10),
"flex": flexValue,
"$jq": $node
};
totalFlex += flexValue;
});
width = $(selector).width();
console.log("%s: width is %d, inner is %d, outer is %d", selector, width, $(selector).innerWidth(), $(selector).outerWidth(true));
for (index in flexInfo) {
node = flexInfo[index];
node.width = Math.floor(width * node.flex / totalFlex - node.borderWidth);
finalFlexTotal += node.width;
console.log(index, node);
node.$jq.css("width", node.width + "px");
}
console.log("%s finalFlexTotal is %d", selector, finalFlexTotal);
}
flexBoxIt("#hbox1");
flexBoxIt("#hbox2");
</script>
</body>
</html>