This solution may meet your requirements, but there is room for optimization and customization based on your specific needs. There is a known issue with the layout when transitioning to a single column view, which can be addressed by setting all margin-top
values to 0
below a certain screen width.
http://example.com/code-sample
$(window).resize(function(e){
var containerWidth = $("#container").width();
$("#container .box").each(function(index, element){
$(this).css("margin-top", 0);
var topPosition = $(this).position().top;
var leftPosition = $(this).position().left;
var targetElement = null;
var htmlElement = $("html")[0];
if (topPosition > 0){
var currentTopPos = topPosition;
while ((targetElement == null || targetElement == htmlElement) && currentTopPos > 0){
currentTopPos -= 10;
targetElement = document.elementFromPoint(leftPosition, currentTopPos);
}
var targetTopPos = $(targetElement).position().top;
var targetHeight = $(targetElement).height();
var negativeMargin = (targetTopPos + targetHeight) - topPosition;
if (negativeMargin < 0){
$(this).css("margin-top", negativeMargin);
}
else if (negativeMargin > 0)
$(this).css("margin-top", 0);
}
});
});