Skip to content

Instantly share code, notes, and snippets.

@blakek
Last active August 29, 2021 15:54
Show Gist options
  • Save blakek/5e33c7e4a35e2dbb154e96847dbc37d7 to your computer and use it in GitHub Desktop.
Save blakek/5e33c7e4a35e2dbb154e96847dbc37d7 to your computer and use it in GitHub Desktop.
Styled Components - columns helper
/**
* Adds `columns` prop allowing setting width based on an object.
* @example <caption>100% width on smaller screens; 1/2 width on medium-sized screen</caption>
* <Component columns={{ md: 6 }} />
* @example <caption>8 columns on smaller screens; 2 columns starting at samm screen</caption>
* <Component columns={{ default: 8, sm: 2 }} />
*/
const columns = css`
width: ${p =>
setColumnWidth(getOr(12, 'columns.default', p), p.theme.gridSettings)};
${({ columns = {}, theme }) =>
Object.entries(columns).map(
([key, value]) =>
key in media.up &&
media.up[key]`
width: ${setColumnWidth(value, theme.gridSettings)};
`
)};
`;
/*************************************************************/
const gridSettings = {
columnWidth: 70,
gutterWidth: 36,
maxWidth: 1236,
totalColumns: 12
}
const getColumnSpanSize = (
columnCount,
{ columnWidth, gutterWidth }
) => {
const columnTotal = columnCount * columnWidth;
const gutterTotal = (columnCount - 1) * gutterWidth;
return columnTotal + gutterTotal;
};
const setColumnWidth = (columns, gridSettings) => {
const { maxWidth } = gridSettings;
const totalWidth = getColumnSpanSize(columns, gridSettings);
return `${getPercentValue(totalWidth, maxWidth)}%`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment