Wurtzite ZnO can be substituted with up to $\ensuremath{\sim}30%$ MgO to form a metastable ${\mathrm{Zn}}_{1\ensuremath{-}x}{\mathrm{Mg}}_{x}\mathrm{O}$ alloy while still retaining the wurtzite structure. Because this alloy has a larger band gap than pure ZnO, ${\mathrm{Zn}}_{1\ensuremath{-}x}{\mathrm{Mg}}_{x}\mathrm{O}∕\mathrm{Zn}\mathrm{O}$ quantum wells and superlattices are of interest as candidates for applications in optoelectronic and electronic devices. Here, we report the results of an ab initio study of the spontaneous polarization of ${\mathrm{Zn}}_{1\ensuremath{-}x}{\mathrm{Mg}}_{x}\mathrm{O}$ alloys as a function of their composition. We perform calculations of the crystal structure based on density-functional theory in the local-density approximation, and the polarization is calculated using the Berry-phase approach. We decompose the changes in polarization into purely electronic, lattice-displacement-mediated, and strain-mediated components, and quantify the relative importance of these contributions. We consider both free-stress and epitaxial-strain elastic boundary conditions, and show that our results can be fairly well reproduced by a simple model in which the piezoelectric response of pure ZnO is used to estimate the polarization change of the ${\mathrm{Zn}}_{1\ensuremath{-}x}{\mathrm{Mg}}_{x}\mathrm{O}$ alloy induced by epitaxial strain.