The merger of two neutron stars has been predicted to produce an optical-infrared transient (lasting a few days) known as a kilonova, powered by the radioactive decay of neutron-rich species synthesized in the merger. Evidence that short gamma-ray bursts also arise from neutron-star mergers has been accumulating. In models of such mergers a small amount of mass ($10^{-4}$-$10^{-2}$ solar masses) with a low electron fraction is ejected at high velocities (0.1-0.3 times light speed) and/or carried out by winds from an accretion disk formed around the newly merged object. This mass is expected to undergo rapid neutron capture (r-process) nucleosynthesis, leading to the formation of radioactive elements that release energy as they decay, powering an electromagnetic transient. A large uncertainty in the composition of the newly synthesized material leads to various expected colours, durations and luminosities for such transients. Observational evidence for kilonovae has so far been inconclusive as it was based on cases of moderate excess emission detected in the afterglows of gamma-ray bursts. Here we report optical to near-infrared observations of a transient coincident with the detection of the gravitational-wave signature of a binary neutron-star merger and of a low-luminosity short-duration gamma-ray burst. Our observations, taken roughly every eight hours over a few days following the gravitational-wave trigger, reveal an initial blue excess, with fast optical fading and reddening. Using numerical models, we conclude that our data are broadly consistent with a light curve powered by a few hundredths of a solar mass of low-opacity material corresponding to lanthanide-poor (a fraction of $10^{-4.5}$ by mass) ejecta.