JSFiddle - React, Tailwind, and code Playground
by JohnJ
HTML
<div id="container" class="width_full">
<div class="parent_width"></div>
<div class="parent_width"></div>
<div class="parent_width"></div>
<div class="parent_width"></div>
<div class="parent_width"></div>
<div class="parent_width"></div>
</div>
<div id="debug"></div>
CSS
#container {
width: 300px;
background-color: red;
height: 100px;
}
.parent_width {
width: 30px;
background-color: green;
height: 50px;
margin: 0 3%;
float: left;
}
.parent_width:first-child {
width:31px;
}
JavaScript
// width_full
$('.width_full').each(function (index, el) {
var $parent = $(el);
var parent_width = $parent.width();
var summ_width = 0;
var $children = $parent.children();
$children.each(function (ind, el) {
var $child = $(el);
summ_width += $child.innerWidth();
});
log('children length', $children.length);
log('summ width', summ_width);
log('parent width', parent_width);
var margin = (parent_width - summ_width) / ($children.length - 1) / 2;
log('margin', margin);
log('parseInt(margin)', parseInt(margin, 10));
var shift = parent_width - (parseInt(margin, 10) * 2 * ($children.length - 1) + summ_width);
var shift_step = parseInt(shift / ($children.length - 1) + 0.5, 10);
log('shift', shift);
log('shift step', shift_step);
$children.each(function (ind, el) {
var $child = $(el);
if (ind == 0) {
$child.css({marginLeft: 0, marginRight: parseInt(margin, 10)});
} else if (ind == $children.length - 1) {
log('shift', shift);
$child.css({marginLeft: parseInt(margin, 10) + shift, marginRight: 0});
} else {
$child.css({marginLeft: parseInt(margin, 10) + shift_step, marginRight: parseInt(margin, 10)});
shift -= shift_step;
}
// $child.text(margin);
});
});
function log(key, value) {
$('#debug').append(key + ': ' + value + '<br />');
}