Phobos and Deimos, the two small satellites of Mars, are thought either to be asteroids captured by the planet or to have formed in a disc of debris surrounding Mars following a giant impact1,2,3,4. Both scenarios, however, have been unable to account for the current Mars system1,2,3,5,6,7. Here we use numerical simulations to suggest that Phobos and Deimos accreted from the outer portion of a debris disc formed after a giant impact on Mars. In our simulations, larger moons form from material in the denser inner disc and migrate outwards due to gravitational interactions with the disc. The resulting orbital resonances spread outwards and gather dispersed outer disc debris, facilitating accretion into two satellites of sizes similar to Phobos and Deimos. The larger inner moons fall back to Mars after about 5 million years due to the tidal pull of the planet, after which the two outer satellites evolve into Phobos- and Deimos-like orbits. The proposed scenario can explain why Mars has two small satellites instead of one large moon. Our model predicts that Phobos and Deimos are composed of a mixture of material from Mars and the impactor.