Substances like phenolphthalein or thymol blue change color depending on what pH they are mixed with. They are pH indicators. This allows them to be used to broadly identify the pH of a substance - but how does it work?
Firstly, the pH can will change the shape of the indicator molecule. Acids and bases are solutions with lots of free H+ or OH- ions. When mixed with an indicator, these reactive ions will add themselves onto or strip the molecule. With new atoms, charges, and bonds, the molecule will form a new shape.
Secondly, the shape of the molecule determines its color. White light is made up of all the different frequencies and colors of light. When passing through a sample, the light is constantly reflected, absorbed, and re-emitted. The amount that any frequency of light is absorbed depends on the shape of the molecule and the bonds it forms.
So the pH changes the shape then the shape changes the color.