In an attempt to improve this answer here: How to make a div stack without spaces and keep order in smaller sizes - in Bootstrap
I was trying to figure out how to create jQuery that will dynamically set margin-top divs based on the total total height compared to the total height of the adjacent div column.
css:
div {outline:solid 1px red; } // Set media container widths small to test code. @media (min-width: 400px) { .container { max-width: 1170px; } .left { max-width:50%; width: 50%; float:left; clear:left; } .right { max-width:50%; width: 50%; float:left; } } @media (min-width: 150px) { .container { max-width: 400px; } .col-sm-12 { width: 100%; } }
Html:
<div id="1" class="left col-sm-12" style="height:100px;background-color:yellow;">DIV 1</div> <div id="2" class="right col-sm-12" style="height:80px;">DIV 2</div> <div id="3" class="left col-sm-12" style="height:50px;background-color:yellow;">DIV 3</div> <div id="4" class="right col-sm-12" style="height:70px;">DIV 4</div> <div id="5" class="left col-sm-12" style="height:20px;background-color:yellow;">DIV 5</div> <div id="6" class="right col-sm-12" style="height:80px;">DIV 6</div> <div id="7" class="left col-sm-12" style="height:50px;background-color:yellow;">DIV 7</div> <div id="8" class="right col-sm-12" style="height:90px;">DIV 8</div>
Js:
$(function () { // Get div by id. var idR = $("div").attr('id'); var idNumder =parseInt(idR); // check if it a right div. if((idNumber % 2 ==0) && (idNumber > 2)){ var className = $("div").attr('class'); var leftHeight = 0; var rightHeight = 0; for(int i =0; i<idNumber; i++){ // count up left side heights. if(className.localeCompare("left")==0){ leftHeight += $("#"+idNumber.ToString()).height; } // count up right side heights. if(className.localeCompare("right")==0){ rightHeight += $("#"+idNumber.ToString()).height; } var diff = leftHeight - rightHeight; // Determine which side is shorter. if(leftHeight > rightHeight){ $("#idR").css({ "margin-top":"-"+ diff + "px", }); } else{ var idL = (idNumber + 1).toString(); $("#idL").css({ "margin-top":"-"+ diff + "px", "clear":"both", }); } } } });
Violin: http://jsfiddle.net/kermit77/hswxc06w/26/

The idea is that the difference in height is applied as a negative top edge to the shorter div, pushing it upward towards the stream above the dive above it.

I'm not sure what I'm doing wrong, I suspect that this is something more. I was messing with him (no pun intended) and can't make him work.
I donβt think it works at all.
I would appreciate any feedback
I solved this with the accepted answer help, see the full code here:
stack overflow
javascript jquery html css css-float
Yvette colomb
source share