when you heat the element (i.e with the bunson burner) the electrons gain energy and become exited, they move up to a higher energy level. the gaps between energy levels are quantised and electrons can only exist on quantised energy levels (not between them) when the electrons fall back down energy levels they gives of a specific amounts/frequency of energy = to the energy gap between the levels they dropped though. the frequency of the energy given out is related a specific colour (frequency=hXwavelength). the gaps between different energy levels is different for different elements therefore the frequency of energy/colour will depend on the gaps and be different for different elements.
sorry that was quite long winded but hope it helps :)