JSFiddle - React, Tailwind, and code Playground
HTML
<table>
<tr>
<td> </td>
<td class="containmentTD">
<div class="draggable"></div>
</td>
<td class="containmentTD">
</td>
</tr>
<tr>
<td> </td>
<td class="containmentTD">
</td>
<td class="containmentTD">
</td>
</tr>
<tr>
<td> </td>
<td class="containmentTD">
</td>
<td class="containmentTD">
</td>
</tr>
</table>
CSS
td { border:1px solid black; width:150px; height:75px; }
div.draggable { width:25px; height:25px; background-color: blue }
.containmentTD { background-color: #BFFBFF }
table { z-index: 100 }
div.draggable { z-index: 120 }
div.containment-indicator { z-index: 110 }
JavaScript
$(document).ready(function(){
//The TD elements that are to be included when
//we find the dimentions of the containment
var td_elements = $(".containmentTD");
//This will hold the extreme points of the containment
var points = {
left: td_elements.eq(0).position().left,
top: td_elements.eq(0).position().top,
right: 0,
bottom: 0
};
//Find the points of the containment
td_elements.each(function() {
var t = $(this);
var p = t.position();
var width = t.width();
var height = t.height();
points.left = Math.min(p.left, points.left);
points.top = Math.min(p.top , points.top );
points.right = Math.max( points.right, p.left + width);
points.bottom = Math.max( points.bottom, p.top + height);
});
//This will only work "perfectly" when all draggables have
//the same dimentions
points.bottom -= $("div.draggable:first").height();
points.right -= $("div.draggable:first").width();
$("div.draggable").draggable({
containment: [points.left, points.top, points.right, points.bottom]
});
//Add a div showing the containment borders (for debugging purposes)
$("<div />")
.addClass("containment-indicator")
.css({
"position": "absolute",
"left": points.left,
"top": points.top,
"width": points.right - points.left,
"height": points.bottom - points.top,
"border": "2px solid red"
})
.appendTo("body");
});