Stellar dynamos generate magnetic fields that are of fundamental importance to the variability and evolution of Sun-like and low-mass stars, and for the development of their planetary systems. As a key to understanding stellar dynamos, empirical relations between stellar parameters and magnetic fields are required for comparison to ab initio predictions from dynamo models. We report measurements of surface-average magnetic fields in 292 M dwarfs from a comparison with radiative transfer calculations; for 260 of them, this is the first measurement of this kind. Our data were obtained from more than 15 000 high-resolution spectra taken during the CARMENES project. They reveal a relation between average field strength, ⟨B⟩, and Rossby number, ...