It’s all about chemistry. Inside an “aerial shell” firework that gets launched into the sky, there’s a “bursting charge,” black powder (aka gunpowder) or a black powder substitute and a bunch of small pellets called “pyrotechnic stars.” The stars are made up of a fuel, an oxidizer, a finely ground metal or metal salt powder, and a binder to hold the ingredients together.
When a firework explodes mid-air thanks to the bursting charge and the black powder, the gas and the heat that are produced ignite the stars. The atoms of the metal powders in the stars absorb that heat energy and their electrons rearrange from their lower-energy ground state to a higher-energy “excited” state. As they come back down to their ground state, the excess energy is emitted as light.
The energy difference between the excited and ground states of the electrons is different for each of the chemical powders used in the stars, and the amount of energy emitted determines what wavelength of light they’ll produce and the color we see. That means that the different types of metals used in the stars each have a characteristic color.
Here are some of the metals and specific compounds that are typically used in fireworks to produce different colors:
Red: strontium (strontium carbonate, SrCO3), for intense reds and lithium (lithium carbonate, Li2CO3, or lithium chloride, LiCl) for medium reds
Orange: calcium (calcium chloride, CaCl2)
Yellow: sodium (sodium nitrate, NaNO3)
Green: barium + chlorine producer (barium chloride, BaCl2)
Blue: copper + chlorine producer (copper chloride, CuCl2)
Purple: strontium + copper compounds
Gold: charcoal, iron, lampback
White/Silver: titanium, aluminum, magnesium, beryllium
For more on the science of fireworks, check out this video by the American Chemical Society: