as Mike ‘Pomax’ Kamermans
suggested, the best way would be detect mouse click and add item dynamically. You can customize the width and height of items by assigning values to item_width
and item_height
.
var item_width=40;
var item_height=40;
var added_items=[];
$(function(){
$('.grid').on('click', function(e){
var x = e.pageX - $(this).offset().left;
var y = e.pageY - $(this).offset().top;
var item=$('<div class="item"></div>');
var left=Math.floor(x/item_width)*item_width;
var top=Math.floor(y/item_height)*item_height;
var position={ 'left':left, 'top':top };
var index=added_items.findIndex(p => p.left == position.left && p.top == position.top);
if(index<0){
added_items.push(position);
item.css('left', left);
item.css('top', top);
item.css('background', "#"+((1<<24)*Math.random()|0).toString(16))
item.appendTo($('.grid'));
}
});
});
.grid {
width:400px;
height:400px;
border:1px solid red;
position:relative;
margin:10px;
}
.item {
width:40px;
height:40px;
position:absolute;
background:red;
}
.item:hover {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid"> </div>
solved CSS huge grid problems