我有一个宽度为200px,高度为500px的主分区.根据一些事件,我需要将宽度为50px和高度为50px的子分区添加到主分区中.我需要从左上到下添加它并向右流动.
|---------------| | | | | 1 | 4 | |-------|-------| | | | | 2 | 5 | |-------|-------| | | | | 3 | 6 | |-------|-------|
我试过这些CSS,但它不起作用.
.SubDiv { height: 50px; width: 50px; background: red; } .MainDiv { max-height: 200px; height: 200px; width: 200px; background: blue; min-width: 100px; direction: inherit; } <div> <div id="SimulationPage"> <div id = "ParentDiv" class="MainDiv"> </div> </div> <input type='button' id = "adddiv" value='add div' /> </div> $(document).ready(function () { $('#adddiv').bind('click',function (eventargs) { $("#ParentDiv").append('<div class="SubDiv"> </div>'); }); });
有人可以帮我实现我想要的.
解决方法
你想要实现的目标不能仅仅在css中完成,因为你在父类中拥有未知数量的子项并且在左右浮动它们,你必须找到最中间的子项并从那里浮动它.
如果jQuery让你高兴(因为你已经在其中标记了这个问题)
here is a solution for dynamic count with jQuery
使用jQuery:
var count = $(".MainDiv").children().length; /*get total childs */ var mid_child = Math.ceil(count / 2) + 1; /* find mid child */ var x = 1; /*parameter to set negtaive margin,to push right float on toP*/ var current_div_number = mid_child; /* div number to set margin */ /*assign class name to 2nd half childs,to float them right through css,can be done through jQuery too!!*/ $(".MainDiv .SubDiv:nth-child(n+" + mid_child + ")").addClass("mid"); /* check each .mid class and assign negative margin-toP*/ $(".MainDiv .mid").each(function (index) { $(".MainDiv .SubDiv:nth-child(" + current_div_number + ")").css('margin-top',-(mid_child * 50) + (50 * x) + 'px'); x = x + 1; current_div_number = current_div_number + 1; });
CSS
.MainDiv > div.mid { float:right; background: green; }