Why do elements emit colors when heated?
Elements emit colours when heated because electrons in atoms can have only certain allowed energies.
Heating an atom excites its electrons and they jump to higher energy levels. When the electrons return to lower energy levels, they emit energy in the form of light.
The colour of the light depends on the difference in energy between the two levels. For example, the red, green, and blue lines in the spectrum of hydrogen arise when the electron drops to level 2 from levels 3, 4, and 5.
Every element has a different number of electrons and a different set of energy levels. Thus, each element emits its own set of colours. See, for example, mercury and neon above. Those colours are as distinctive to each element as fingerprints are to people.