The formation mechanisms of the ice giants Uranus and Neptune, and the origin of their elemental and isotopic compositions, have long been debated. The density of solids in the outer protosolar nebula is too low to explain their formation, and spectroscopic observations show that both planets are highly enriched in carbon, very poor in nitrogen, and the ices from which they originally formed might had deuterium-to-hydrogen ratios lower than the predicted cometary value, unexplained properties observed in no other planets. Here we show that all these properties can be explained naturally if Uranus and Neptune both formed at the carbon monoxide iceline. Due to the diffusive redistribution of vapors, this outer region of the protosolar nebula intrinsically has enough surface density to form both planets from carbon-rich solids but nitrogen-depleted gas, in abundances consistent with their observed values. Water rich interiors originating mostly from transformed CO ices reconcile the D/H value of Uranus and Neptunes building blocks with the cometary value. Finally, Our scenario generalizes a well known hypothesis that Jupiter formed on an iceline (water snowline) for the two ice giants, and might be a first step towards generalizing this mechanism for other giant planets.