Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Changing font color based on gradient color of background.

I am building a site with a gradient for a background. It will be yellow and blue. I need to adjust the font color based on the background color. Is there a way to do that without manually changing the color and adjusting in media queries?

1 Answer

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

Hi, Ted. As far as I know, this isn't possible with CSS alone, but you could do it with JavaScript. I'm not sure of the actual code, but you might be able to Google it. Another option would be to do it with Sass (a CSS preprocessor) but if you aren't familiar with it, then JS might be your best bet if you don't want to do it manually.

Thank you. I just finished the basic Sass course and found the following code for Sass:

@function set-button-text-color($color) {
    @if (lightness( $color ) > 40) {
      @return #000000;
    }
    @else {
      @return #FFFFFF;
    }
}

I am not sure if that will read the gradient or if it just looks at the set background color. I will have to figure that out.

I also found a code with contrast for Sass, but both codes appear to require knowing what the background is. In a gradient, you don't know what the background value is on a particular place on the page.

Ryan Field
Ryan Field
Courses Plus Student 21,242 Points

Yeah, I suppose that's true. I thought that maybe you knew which parts you would need to change beforehand and just didn't want to go changing everything manually. If it's going to be unknown which parts are which colour, then you'll most likely need a JavaScript solution.

I searched jQuery and only saw a solution when you knew the background color. Do you have any suggestions on approach to the coding?

Ryan Field
Ryan Field
Courses Plus Student 21,242 Points

I'm not too keen on colour calculations, but after a bit of fishing around on the internet, I came up with this pen. You can change the CSS colour in the middle panel and then hit the button and JS will run and change the text to either black or white, depending on which has the better contrast for readability.

Hmm. I think I will add a semi-transparent background to the elements to ensure font contrast and get the site up. Once all the other bells and whistles are functioning the way I want I will revisit this issue.

Thank you for your thoughts.