Skip to content

Instantly share code, notes, and snippets.

@allybee
Last active April 21, 2016 16:25
Show Gist options
  • Save allybee/ac693222c4623699560f055f07e23191 to your computer and use it in GitHub Desktop.
Save allybee/ac693222c4623699560f055f07e23191 to your computer and use it in GitHub Desktop.
A Sass and JavaScript function which returns either a light or dark color by deciding which contrasts more with the color using the YIQ color space.
// Returns either the $light or $dark color by deciding which contrasts more
// with $color using the YIQ color space (https://en.wikipedia.org/wiki/YIQ).
// This can be used to get a readable font color for a given background color.
//
// When $color is null, this function returns null.
@function contrast-color($color, $dark: 'black', $light: 'white') {
@if $color == null {
@return null;
}
$r: red($color);
$g: green($color);
$b: blue($color);
$yiq: (($r*299) + ($g*587) + ($b*114)) / 1000;
@return if(($yiq >= 128), $dark, $light);
}
// Returns either the darkColor or lightColor color by deciding which contrasts more
// with testColor using the YIQ color space (https://en.wikipedia.org/wiki/YIQ).
// This can be used to get a readable font color for a given background color.
const getContrastColorFromHexColor = function ( testColor, darkColor, lightColor ) {
'use strict'
// Remove leading '#'
const c = testColor.replace( /^#/, '' )
const d = darkColor ? darkColor.replace( /^#/, '' ) : '000000'
const l = lightColor ? lightColor.replace( /^#/, '' ) : 'FFFFFF'
// Check for a valid hexadecimal color
const isValidHexColor = function ( color ) {
return /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/.test( color )
}
if ( [c, d, l].every( isValidHexColor ) == false ) {
console.error( 'You must provide valid six digit hexadecimal colors.' )
return false
}
// Get the contrast color by testing with the YIQ color space
const r = parseInt( c.substr( 0, 2 ), 16 )
const g = parseInt( c.substr( 2, 2 ), 16 )
const b = parseInt( c.substr( 4, 2 ), 16 )
const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000
const contrastColor = (yiq >= 128) ? d : l
// Return the contrast color
return '#' + contrastColor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment