Elements like mercury are formed by nuclear fusion in stars. Hydrogen atoms are fused together to form helium atoms, and then more elements up to iron. Elements heavier than iron are formed in supernovae – exploding stars.
On earth, mercury is very rare. It is found in the earth’s crust, sometimes on its own as a native metal, but usually in minerals like cinnabar (HgS).