$(document).ready(function(e) { for (var count = 0; count < 5; count++) { for (var iter = 0; iter < 5; iter++) { $(".content").append("<div id='" + count + "_" + iter + "' class='Box'><p>" + count + "_" + iter + "</p></div>"); $(".content div:last").width(Math.round((Math.random() * 100) + 50)); $(".content div:last").height($(".content div:last").width()); } } });
.Box { background: #FF0004; margin: 10px; float: left; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div class="content"> </div> </body>
我试图更好地理解浮动属性逻辑和浮动元素在彼此“堆叠”时定位的原因.例如(从小提琴截取的截图):
是什么让3_3重新定位到如下所示的位置,当屏幕变大?
据W3Schools说:
If you place several floating elements after each other,they will float next to each other if there is room.
所以问题是,“空间”意味着什么,以及控制浮动元素位置的逻辑是什么?
这个SO帖子的答案:CSS Float explanation似乎是相关的,但它似乎没有解释为什么浮动元素在某个位置停止.
解决方法
When you float a block element,you are telling the browser to position it next to the prevIoUs floated object,so long as the container is wide enough (otherwise it will drop below the prevIoUs object).
正如作者所提到的,这是一种粗略的简化.规范的Section 9.5.1有一个所有精确规则的列表,但我不打算在这里引用整个事情,因为这是一个很长的阅读,只有某些点在这里是相关的.当我逐步介绍你的小提琴中发生的事情时,我会引用相关的观点.
比较你的两个截图.注意已经改变位置的两个方框,3_2和3_3,以及它们周围的方框,2_4,3_0和3_1.
之前
后
当屏幕变大时,您可以腾出空间让3_2从2_4旁边的原始位置向上移动,然后在3_1旁边移动:
- A left-floating Box that has another left-floating Box to its left may not have its right outer edge to the right of its containing block’s right edge. (Loosely: a left float may not stick out at the right edge,unless it is already as far to the left as possible.) An analogous rule holds for right-floating elements.
- A floating Box must be placed as high as possible.
这反过来为下一个浮动盒子腾出空间,使其尽可能地占据顶部和尽可能远的空间,遵循与上述相同的规则.结果,3_3漂浮起来,只停止了3_2,然后它沿着水平轴尽可能地向左浮动,停止了2_4.请注意,即使看起来3_3应该能够适合2_4和3_2之间,但事实并非如此,因为边距必须得到尊重(这就是上面“外边缘”的含义).
此时,除上述第8项和第9项外,还适用以下项目:
- If the current Box is left-floating,and there are any left-floating Boxes generated by elements earlier in the source document,then for each such earlier Box,either the left outer edge of the current Box must be to the right of the right outer edge of the earlier Box,or its top must be lower than the bottom of the earlier Box. Analogous rules hold for right-floating Boxes.
由于3_3太大,它会从第一行浮动框产生明显的向下突出.这有效地增加了第一条线的高度. 3_3之后的所有其他浮动元素必须保留在它们自己的行上,并且第二行浮点数不得与3_3的下边缘边缘相交.这主要由第5项管理.