Skip to content

Instantly share code, notes, and snippets.

@mundry
Created July 2, 2014 15:04
Show Gist options
  • Save mundry/ea7f774e08a9d8668373 to your computer and use it in GitHub Desktop.
Save mundry/ea7f774e08a9d8668373 to your computer and use it in GitHub Desktop.
Script to generate CSS rules for columns of a grid system.
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Number of digits after the dot to be output in the CSS rule.
PRECISION = 8
def generate_grid(columns, className, collapseThreshold=1):
"""
Generates CSS code for a grid system.
columns - The number of columns the grid consists of.
className - The name of each column rule. The name will be
suffix with a dash and the column number.
collapseThreshold - The number of columns sharing a width value.
"""
if collapseThreshold > columns or columns % collapseThreshold != 0:
exit(1)
# Preprocessing to get the formatting right.
# The percentage values for each column as strings aligned by the dot.
widths = []
# The most digits after the dot of a width value.
maxPrecision = 0
for i in range(1, columns + 1):
if i % collapseThreshold == 0:
precision = PRECISION
width = ''.join(('{:>', str(precision + 4), '.', str(precision), 'f}')).format(100.0 / columns * i)
for j in range(len(width) - 1, 3, -1):
if width[j] != '0':
break
precision -= 1
if precision > maxPrecision:
maxPrecision = precision
widths.append(width[:3 + precision + (0 if precision == 0 else 1)])
stylesheet = []
for i in range(columns):
stylesheet.append(className if className[0] == '.' else '.{}'.format(className))
stylesheet.append('-')
stylesheet.append(str(i + 1))
if (i + 1) % collapseThreshold == 0:
stylesheet.append(' ' * (2 if columns > 9 and i < 9 else 1))
if collapseThreshold > 1:
stylesheet.append(' ')
stylesheet.append('{ width: ')
widthLength = len(widths[i / collapseThreshold])
if maxPrecision > 0:
if widthLength == 3:
widthLength += maxPrecision + 1
else:
widthLength += (maxPrecision - (widthLength - 4))
widthLength += 2 # for '%;'
stylesheet.append(''.join(('{:<', str(widthLength), '}')).format('{}%;'.format(widths[i / collapseThreshold])))
stylesheet.append(' }')
else:
stylesheet.append(',')
stylesheet.append('\n')
return ''.join(stylesheet)
if __name__ == "__main__":
print generate_grid(16, 'column')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment