Aims. We compute for the first time self-consistent models of planet growth that include the effect of envelope enrichment. The change in envelope metallicity is assumed to be the result of planetesimal disruption or icy pebble sublimation.

Methods. We solved internal structure equations taking into account global energy conservation for the envelope to compute in situ planetary growth. We considered different opacities and equations of state suited for a wide range of metallicities.

Results. We find that envelope enrichment speeds up the formation of gas giants. It also explains naturally the formation of low- and intermediate-mass objects with large fractions of H-He (~20–30% in mass). High-opacity models explain the metallicity of the giant planets of the solar system well, while low-opacity models are suited to explain the formation of low-mass objects with thick H-He envelopes and gas giants with sub-solar envelope metallicities. We find good agreement between our models and the estimated water abundance for WASP-43b. For HD 189733b, HD 209458b, and WASP-12b we predict fractions of water higher than what is estimated from observations by at least a factor ~2.

Conclusions. Envelope enrichment by icy planetesimals is the natural scenario to explain the formation of a wide variety of objects, ranging from mini-Neptunes to gas giants. We predict that the total and envelope metallicity decrease with planetary mass.