Find Appropriate Colour In PHP

25th February 2009 - 1 minute read time

Use the following function if you want to print the text in a particular colour, depending on what the background colour is.

  1. function opposite($color) {
  2. $white = 0;
  3. for ($i = 0; $i < 6; $i += 2) {
  4. $white += base_convert(substr($color,$i,2),16,10) < 127 ? 1 : 0;
  5. }
  6. return $white <= 2 ? "000000" : "ffffff";
  7. }

It works by looking at the colour and seeing how much of it is white. If greater than two parts are significantly white then the color returned is black, otherwise white is returned.

Here are some examples to test the function out.

  1. echo '<span style="background-color:#ffffff;color:#'.opposite('ffffff').'">XXXXXX</span>';
  2. echo '<span style="background-color:#000000;color:#'.opposite('000000').'">XXXXXX</span>';
  3. echo '<span style="background-color:#fedbad;color:#'.opposite('fedbad').'">XXXXXX</span>';
  4. echo '<span style="background-color:#123456;color:#'.opposite('123456').'">XXXXXX</span>';
  5. echo '<span style="background-color:#fe13ef;color:#'.opposite('fe13ef').'">XXXXXX</span>';

 

Comments

Permalink

Would love to perpetually get updated great web blog!

audreyknudson463 (Fri, 05/25/2018 - 19:21)

Add new comment

The content of this field is kept private and will not be shown publicly.