The main pigment in your skin is melanin. It protects your skin from damage caused by the rays of the sun. When you get more sun, your skin compensates by producing more melanin, and you get a tan.
But sunlight is needed to make Vitamin D in your skin. So when people started living in northern countries that don’t get as much sun as tropical countries do, they evolved to produce less melanin, so what little sunlight there was could get into the skin and produce enough Vitamin D.
When ultraviolet light from the sun damages the DNA in your skin, the damage is detected, and the skin produces more melanin. The melanin produced absorbs ultraviolet light very well, and protects the DNA in the skin from further damage. If there is too much damage to the DNA, skin cancer can result.
Melanin is found in other places in the body besides the skin. It is the pigment that colors hair, and it is present in the iris of the eye. Even blue-eyed people usually have small areas of the iris that contain melanin.
There are many types of melanin, and they have different colors. Brown hair, black hair, blond hair, and red hair are colored by different amounts of the different types of melanin.
One type of melanin, pheomelanin, is pinkish or reddish, and is what colors red hair. Another form, eumelanin, can be black or brown. If most of the melanin in hair is missing, except for a little bit of black eumelanin, we get gray hair. If most melanin is missing except for a little bit of brown eumelanin, we get blond hair.
Other animals also use melanin for coloration and protection from ultraviolet light. Octopi and squid use it to make the black ink they produce when attacked. Some bacteria and fungi use it as a sunscreen and as an antioxidant, and it can protect some microorganisms from attack by a host animal’s immune system.