Dynamic side-by-side DIVs resize
After many attempts, I finally found this pretty simple solution to archive what I wanted to do. The div will always handle its size with its immediate neighbor.
by Kostya Tretyak
January 02, 2015
HTML
<div class="wrapper">
<div class="base" style="background:#FFB2B2;"></div>
<div class="base" style="background:#94FF94;"></div>
<div class="base" style="background:#80E6FF;"></div>
<div class="base"></div>
</div>
CSS
html, body {
height: 100%;
width: 100%;
overflow: hidden;
}
.wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
}
.wrapper.resizing {
overflow: hidden;
}
.base {
overflow: hidden;
padding: 5px;
height: 30px;
border: 1px solid black;
border-right: 3px solid #6666FF;
-moz-box-sizing:border-box;
box-sizing: border-box;
}
JavaScript
$(document).ready(function () {
var allYourBase = $(".base");
var count_el = allYourBase.size();
var w = Math.round(100 / count_el) + "%";
allYourBase.css("width", w).html('<span>' + w + '</span>');
allYourBase.filter(":not(:last-child)").resizable({
handles: 'e',
distance: 5,
start: function (event, ui) {
// just remember the total width of self + neighbor
this.widthWithNeighbor = ui.originalSize.width + ui.element.next().outerWidth();
// fix FF resizing issue sometimes cause div to overflow
$(this).parent().addClass("resizing");
},
resize: function (event, ui) {
$(".base span").each(function(idex, ui){
var cur_width = $(this).parent().outerWidth();
var total_widht = $(".wrapper").outerWidth();
var percent = Math.round((cur_width) / total_widht * 100);
$(this).text(percent + "%");
});
// and just subtract it!
ui.element.next().width(this.widthWithNeighbor - ui.size.width);
},
stop: function (event, ui) {
// clean up, is this needed?
delete this.widthWithNeighbor;
$(this).parent().removeClass("resizing");
}
}).on('resize', function (event) {
event.stopPropagation();
});
});