To enhance the answer provided in this post: How to stack divs without spaces and maintain order on smaller screens using Bootstrap
I've been exploring ways to develop a jQuery script that dynamically adjusts the margin-top
of div elements based on their accumulated height compared to adjacent columns.
The CSS:
div {outline:solid 1px red; }
// Setting small media container widths for code testing.
@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%;
}
}
The 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>
The JavaScript:
$(function () {
// Extract div by id.
var idR = $("div").attr('id');
var idNumber = parseInt(idR);
// Checking if it's a right-aligned div element.
if((idNumber % 2 == 0) && (idNumber > 2)){
var className = $("div").attr('class');
var leftHeight = 0;
var rightHeight = 0;
for(int i = 0; i < idNumber; i++){
// Calculating left side heights accumulation.
if(className.localeCompare("left") == 0){
leftHeight += $("#"+idNumber.toString()).height;
}
// Calculating right side heights accumulation.
if(className.localeCompare("right") == 0){
rightHeight += $("#"+idNumber.toString()).height;
}
var diff = leftHeight - rightHeight;
// Determining 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",
});
}
}
}
});
The Fiddle: http://jsfiddle.net/kermit77/hswxc06w/26/
https://i.sstatic.net/56ykK.png
The concept behind this approach is to apply the difference in height as a negative top margin to the shorter div, aligning it with the one above.
https://i.sstatic.net/y2aw1.png
Although I'm encountering issues and suspect multiple errors, I haven't been able to get it to function correctly through trial and error.
Any feedback or guidance would be greatly appreciated.
With assistance from the accepted solution, I managed to resolve this challenge. Full code available here: