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.

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

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.

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




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.