I'm creating a responsive grid system system that uses percentages to size elements. I tried building it with floats, inline-block, and tables. I'm sure I want to stick with inline-block because it allows me to center items vertically and horizontally. I built my design without using margins. I am using the border-box model so padding and borders won't collapse the rows.
However, I'm wanting to upgrade my grid system to allow you to set margins without breaking the row. Basically a jquery custom built "box-sizing: margin-box;".
My hope is that I can use jquery to subtract the percentage width of margins from the percentage width of the containers. However, this in and of itself doesn't work well because inline-block adds extra white space. So in addition to my current plan, I am using jquery to subtract the extra white space from margin-right. I've actually gotten it working! It does what I want it to, but I'm facing a minor problem.
The calculations are not precise enough and the rows end up coming a few pixels different from each other. It means I don't get even straight lines at the end of each row. The overall rows come out to different lengths. How do I make the calculations precise enough to line up accurately?
Here is the code:
boxsizing = function(container){
jQuery(container).each(function() {
var el = jQuery(this);
el.css('width', '');
el.css('margin-right', '');
var parentWidth = el.parent().width();
var childWidth = el.outerWidth(false);
//finds ratio of child container to parent container
var childDecimal = (childWidth / parentWidth);
//converts child container to a decimal
childDecimal = Math.round(childDecimal*10000);
//gets font size
var fontSize = el.css('font-size');
//removes px from the end
var fontSize = fontSize.slice (0, -2);
//calculates white space on the right of each div
var whiteSpace = 0.29*fontSize;
var fontDecimal = whiteSpace / parentWidth;
//converts white space to a decimal
fontDecimal = Math.round(fontDecimal*10000)
//subtracts extra white space from margin-right
var newMarginRight = el.css('margin-right');
var newMarginRight = newMarginRight.slice (0, -2);
newMarginRight = Math.round(newMarginRight);
newMarginRight = newMarginRight - whiteSpace;
newMarginRight = newMarginRight / parentWidth;
newMarginRight = Math.round(newMarginRight*10000);
newMarginRight = newMarginRight/100;
//finds margin to parent ratio
var marginDecimal = (el.outerWidth(true) - childWidth)/parentWidth;
//converts margin to decimal form
marginDecimal = Math.round(marginDecimal*10000);
//take previous width and subtract margin from it
var newWidth = (childDecimal - marginDecimal)/100;
//set the element's width to the new calcualted with and set margin right to the updated value
el.css('width', newWidth + "%");
el.css('margin-right', newMarginRight + "%");
});
}
jQuery(window).load(function() {
boxsizing('.margins');
});