:
<div class="classroom">
<div class="student">
<img class="student-image" src="http://dnqgz544uhbo8.cloudfront.net/_/fp/img/home/f.AmzRdUdc4pEtCuGvU03WXQ.jpg">
</div>
<div class="student">
<img class="student-image" src="http://dnqgz544uhbo8.cloudfront.net/_/fp/img/home/k.jXX55KhHUWZGTAb-GpPkdg.jpg">
</div>
<div class="student">
<img class="student-image" src="http://dnqgz544uhbo8.cloudfront.net/_/fp/img/home/c.ZKQXc2Kc8-po-OK6AhDbtw.jpg">
</div>
</div>
我想要将所有的“students” div元素显示在同一行,因此我使用了以下CSS样式:
body {
padding: 0;
margin: 0;
overflow: hidden;
}
html, body {
height: 100%;
}
.classroom {
position: relative;
height: 100%;
}
.classroom .student {
position: relative;
height: 100%;
float: left;
}
.classroom .student .student-image {
height: 100%;
}
为了让学生在“教室”div中有足够的空间,我使用jQuery来计算“教室”的宽度:
$(document).ready(function() {
var w = 0;
$(".student").each(function() {
w += $(this).width();
});
$(".classroom").width(w);
});
很遗憾,结果不是我预期的。最后一个“学生”div下移了一行(好像没有分配
float:left;
)。更奇怪的是,当将“教室”div的宽度增加1像素时,div返回到第一行的位置。我制作了这些jsfiddles: 在这里http://jsfiddle.net/U3gBG你可以看到问题。点击结果面板并使用箭头键向下和向右滚动。
在这里http://jsfiddle.net/U3gBG/1/你可以看到在计算后将“教室”div的宽度增加1的结果(“教室”的宽度等于“学生”宽度之和加1像素)。这个结果就是我需要的。
我不明白为什么需要将父div的宽度增加1?为什么不只是将所有子div的宽度相加就可以了?
Math.ceil()
可能是你的答案。 - Ja͢ck