Skip to content

Instantly share code, notes, and snippets.

@doubleedesign
Last active April 7, 2023 01:33
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 doubleedesign/0588275dcbb63d16134ecff0ab19d8cd to your computer and use it in GitHub Desktop.
Save doubleedesign/0588275dcbb63d16134ecff0ab19d8cd to your computer and use it in GitHub Desktop.
Shortcut function for choosing text colour based on background colour using Styled Components + Polished
import { meetsContrastGuidelines } from 'polished';
import { ContrastScores } from 'polished/lib/types/color';
type WCAGLevel = keyof ContrastScores;
export function contrastTextColour(color: string, wcag: WCAGLevel = 'AA') {
const scores = meetsContrastGuidelines(color, '#fff');
if(scores[wcag]) {
return '#fff';
}
else {
return '#000';
}
}
import styled from 'styled-components';
import { darken } from 'polished';
import { ThemeColor } from '../../types';
import { contrastTextColour } from '../../theme-utils';
interface ButtonProps {
color: ThemeColor // See https://gist.github.com/doubleedesign/b53af9d8c66c53eb909279637124e544 for how this type works
}
export const StyledButton = styled.button<ButtonProps>`
background: ${({ theme, color }): string => theme.colors[color]};
color: ${({ theme, color }): string => contrastTextColour(theme.colors[color])};
text-decoration: underline;
text-decoration-color: transparent;
// ... more styles
&:hover, &:focus, &:active {
// theme.colors[color] may initially be "undefined" briefly when the component first loads,
// that's why there's a && conditional here
background: ${({ theme, color }): string => theme.colors[color] && darken(0.1, theme.colors[color])};
};
&:focus {
text-decoration-color: currentColor;
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment