The effects of hydrocarbon reactions and diamond precipitation on the internal structure and evolution of icy giant planets such as Neptune and Uranus have been discussed for more than three decades1. Inside these celestial bodies, simple hydrocarbons such as methane, which are highly abundant in the atmospheres2, are believed to undergo structural transitions3,4 that release hydrogen from deeper layers and may lead to compact stratified cores5,6,7. Indeed, from the surface towards the core, the isentropes of Uranus and Neptune intersect a temperature–pressure regime in which methane first transforms into a mixture of hydrocarbon polymers8, whereas, in deeper layers, a phase separation into diamond and hydrogen may be possible. Here we show experimental evidence for this phase separation process obtained by in situ X-ray diffraction from polystyrene (C 8 H 8 ) n samples dynamically compressed to conditions around 150 GPa and 5,000 K; these conditions resemble the environment around 10,000 km below the surfaces of Neptune and Uranus9. Our findings demonstrate the necessity of high pressures for initiating carbon–hydrogen separation3 and imply that diamond precipitation may require pressures about ten times as high as previously indicated by static compression experiments4,8,10. Our results will inform mass–radius relationships of carbon-bearing exoplanets11, provide constraints for their internal layer structure and improve evolutionary models of Uranus and Neptune, in which carbon–hydrogen separation could influence the convective heat transport7.