The cosmic origin of elements heavier than iron has long been uncertain. Theoretical modelling shows that the matter that is expelled in the violent merger of two neutron stars can assemble into heavy elements such as gold and platinum in a process known as rapid neutron capture (r-process) nucleosynthesis. The radioactive decay of isotopes of the heavy elements is predicted to power a distinctive thermal glow (a ‘kilonova’). The discovery of an electromagnetic counterpart to the gravitational-wave source GW170817 represents the first opportunity to detect and scrutinize a sample of freshly synthesized r-process elements. Here we report models that predict the electromagnetic emission of kilonovae in detail and enable the mass, velocity and composition of ejecta to be derived from observations. We compare the models to the optical and infrared radiation associated with the GW170817 event to argue that the observed source is a kilonova. We infer the presence of two distinct components of ejecta, one composed primarily of light (atomic mass number less than 140) and one of heavy (atomic mass number greater than 140) r-process elements. The ejected mass and a merger rate inferred from GW170817 imply that such mergers are a dominant mode of r-process production in the Universe.