The origin of magnetic fields in white dwarfs remains a fundamental unresolved problem in stellar astrophysics. In particular, the very different fractions of strongly (more than about a megagauss) magnetic white dwarfs in evolutionarily linked populations of close white dwarf binary stars cannot be reproduced by any scenario suggested so far. Strongly magnetic white dwarfs are absent among detached white dwarf binary stars that are younger than approximately a billion years. In contrast, of cataclysmic variables (semi-detached binary star systems that contain a white dwarf) in which the white dwarf accretes from a low-mass star companion, more than a third host a strongly magnetic white dwarf1. Here we present binary star evolutionary models that include the spin evolution of accreting white dwarfs and crystallization of their cores, as well as magnetic field interactions between the stars. We show that a crystallization- and rotation-driven dynamo similar to those working in planets and low-mass stars2 can generate strong magnetic fields in the white dwarfs in cataclysmic variables, which explains their large fraction among the observed population. When the magnetic field generated in the white dwarf connects with that of the secondary star in the binary system, synchronization torques and reduced angular momentum loss cause the binary to detach for a relatively short period of time. The few known strongly magnetic white dwarfs in detached binaries, such as AR Scorpii3, are in this detached phase. The complex evolutionary dance of the strongly magnetic white dwarf in a compact binary system can be effectively modelled by considering spin evolution, core crystallization and a rotation-driven dynamo similar to that in planets and low-mass stars.