The discovery of Uranus' and Neptune's non-dipolar, non-axisymmetric magnetic fields destroyed the picture-established by Earth, Jupiter and Saturn-that planetary magnetic fields are dominated by axial dipoles. Although various explanations for these unusual fields have been proposed, the cause of such field morphologies remains unexplained. Planetary magnetic fields are generated by complex fluid motions in electrically conducting regions of the planets (a process known as dynamo action), and so are intimately linked to the structure and evolution of planetary interiors. Determining why Uranus and Neptune have different field morphologies is not only critical for studying the interiors of these planets, but also essential for understanding the dynamics of magnetic-field generation in all planets. Here we present three-dimensional numerical dynamo simulations that model the dynamo source region as a convecting thin shell surrounding a stably stratified fluid interior. We show that this convective-region geometry produces magnetic fields similar in morphology to those of Uranus and Neptune. The fields are non-dipolar and non-axisymmetric, and result from a combination of the stable fluid's response to electromagnetic stress and the small length scales imposed by the thin shell.