Skip to content

Instantly share code, notes, and snippets.

@AtkinsSJ
Last active December 11, 2015 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AtkinsSJ/4598634 to your computer and use it in GitHub Desktop.
Save AtkinsSJ/4598634 to your computer and use it in GitHub Desktop.
/**
* Generates the css for a grid system and returns it as a string.
*/
function getGridSystemCSS(columns, columnWidth, gutterWidth) {
var totalWidth = columns * (columnWidth + gutterWidth),
fluidGutterWidth = percentageRoundedTo3DP(gutterWidth / totalWidth); // Get a number with up to 3 decimal places
var css =[".grid-wrapper {"
, " max-width: " + totalWidth + "px;"
, " margin-left: -" + fluidGutterWidth + "%;"
, " overflow:hidden;"
, "}"
, ".grid {"
, " float: left;"
, " margin-left: " + fluidGutterWidth + "%;"
, "}"];
var cssWidth;
for (var i = 1; i <= columns; i++) {
css.push(".grid-" + i + " {");
cssWidth = percentageRoundedTo3DP(((i * (columnWidth + gutterWidth)) - gutterWidth) / totalWidth);
css.push(" width: " + cssWidth + "%;");
css.push("}");
}
return css.join("\n");
}
/**
* Returns the given number, 'n' (between 0 and 1) as a percentage,
* rounded to three decimal places.
*/
function percentageRoundedTo3DP(n) {
return Math.round(n * 100 * 1000) / 1000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment