Using cosmological simulations , we address the properties of high-redshift star-forming galaxies ( SFGs ) across their main sequence ( MS ) in the plane of star-formation rate ( SFR ) versus stellar mass . We relate them to the evolution of galaxies through phases of gas compaction , depletion , possible replenishment , and eventual quenching . We find that the high-SFR galaxies in the upper envelope of the MS are compact , with high gas fractions and short depletion times ( “ blue nuggets ” ) , while the lower-SFR galaxies in the lower envelope have lower central gas densities , lower gas fractions and longer depletion times , consistent with observed gradients across the MS. Stellar-structure gradients are negligible . The SFGs oscillate about the MS ridge on timescales \sim 0.4 ~ { } t _ { \mathrm { Hubble } } ( \sim 1 Gyr at z \sim 3 ) . The propagation upwards is due to gas compaction , triggered , e.g. , by mergers , counter-rotating streams , and/or violent disc instabilities . The downturn at the upper envelope is due to central gas depletion by peak star formation and outflows while inflow from the shrunken gas disc is suppressed . An upturn at the lower envelope can occur once the extended disc has been replenished by fresh gas and a new compaction can be triggered , namely as long as the replenishment time is shorter than the depletion time . The mechanisms of gas compaction , depletion and replenishment confine the SFGs to the narrow ( \pm 0.3 dex ) MS. Full quenching occurs in massive haloes ( M _ { \mathrm { vir } } > 10 ^ { 11.5 } ~ { } M _ { \odot } ) and/or at low redshifts ( z < 3 ) , where the replenishment time is long compared to the depletion time , explaining the observed bending down of the MS at the massive end .