jQuery: css margin based on the amount of elements in container?

I'm trying to create a simple collage creator using jquery.

what I need to do is to have a margin of 1% between each element (collage).

But at the same time I need the collages to have 0 margin from their container.

I hope that makes sense.

I've created this FIDDLE so you know what I mean.

when you run the code, just click on the button 4 times and you should see the collages being created inside the container perfectly fine BUT there is a margin between their container and its children elements which is not wanted.

Is there any way to sort this issue out?

This is my code:

$('#colBtn').live('click', function(){

    $('.lable').show();
    $('#reset').show();
    $('#fileField').show();
    $('#sbs').show();
    var width = $('#width').val();
    var height = $('#height').val();

    $('#main').append('<div class="droppable" style="width:'+width+';height:'+height+';overflow: hidden;  position:relative;float:left; margin:1%;"></div>');


    $('#layout').text($('#main').html());
    return false;
});

在这里输入图像描述


What you're looking for is a negative margin.

put another div in your #main div and give it a negative margin.

margin: 0 -1%

This will make it as if it had no margin since you have

overflow: hidden

set to your main container.

Something like this: Fiddle

Hope this gets you closer to your goal ;)


By the above given figure. The main issue seems like figuring out which is the first item and which is the last item of a row. having dynamic number of items in a row.

I just figure out the first item and last item you can use it to adjust margin.

function fix(){
var $item = $('.droppable');
var parentWidth = $item.parent().width();
var itemWidth = $item.outerWidth(true);
var itemInLine = Math.floor(parentWidth/itemWidth);
var totalItems = $item.length;
var rows = totalItems / itemInLine;

var lastItem = 0;
var firstItem = 1;
    for(var i = 1; i< rows + 1; i++){
    lastItem = i * itemInLine;
    $('.droppable:nth-child('+ lastItem +')').css({'margin-top':'0px','margin-right':'0px'});
    firstItem = (i * itemInLine) - itemInLine + 1;
    $('.droppable:nth-child('+ firstItem +')').css({'margin-top':'0px'});
    }
}
链接地址: http://www.djcxy.com/p/34254.html

上一篇: C ++概念与朋友

下一篇: jQuery:基于容器中元素的数量的CSS边距?