Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Last active October 14, 2019 15:51
Show Gist options
  • Save wojtekmaj/64bb4cb725ad79c6655da8b14ad72281 to your computer and use it in GitHub Desktop.
Save wojtekmaj/64bb4cb725ad79c6655da8b14ad72281 to your computer and use it in GitHub Desktop.
Generate CSS line background in styled-components.
function toPx(val) {
return typeof val === 'number' ? `${val}px` : val;
}
/**
* Creates a background with a single line, e.g. for simulating underline.
*
* Sample usage in styled-components:
* ${props => lineBackground('to bottom', '2px', props.color)}
*
* @param {String} direction Background direction, e.g. "to bottom" or "45deg"
* @param {String|Number} width Line width, e.g. '2px' or 2
* @param {String} color Line color, e.g. 'red'
*/
export function lineBackground(direction, offset, width, color) {
const widthPx = toPx(width);
const offsetPx = toPx(offset);
const lineStart = offsetPx;
const lineEnd = `calc(${lineStart} + ${widthPx})`;
return `background: linear-gradient(
${direction},
transparent ${lineStart},
${color} ${lineStart},
${color} ${lineEnd},
transparent ${lineEnd}
);`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment