Most molecular clouds are filamentary or elongated1-3. For those forming low-mass stars (<8 solar masses), the competition between self-gravity and turbulent pressure along the dynamically dominant intercloud magnetic field (10 to 100 parsecs) shapes the clouds to be elongated either perpendicularly4or parallel5to the fields. A recent study6also suggested that on the scales of 0.1 to 0.01 parsecs, such fields are dynamically important within cloud cores forming massive stars (>8 solar masses). But whether the core field morphologies are inherited from the intercloud medium or governed by cloud turbulence is unknown, as is the effect of magnetic fields on cloud fragmentation at scales of 10 to 0.1 parsecs7,8,9. Here we report magnetic-field maps inferred from polarimetric observations of NGC 6334, a region forming massive stars, on the 100 to 0.01 parsec scale. NGC 6334 hosts young star-forming sites10-12where fields are not severely affected by stellar feedback, and their directions do not change much over the entire scale range. This means that the fields are dynamically important. The ordered fields lead to a self-similar gas fragmentation: at all scales, there exist elongated gas structures nearly perpendicular to the fields. Many gas elongations have density peaks near the ends, which symmetrically pinch the fields. The field strength is proportional to the 0.4th power of the density, which is an indication of anisotropic gas contractions along the field. We conclude that magnetic fields have a crucial role in the fragmentation of NGC 6334.