For the same stellar mass, physically smaller star-forming galaxies are also metal richer (Ellison et al. 2008). What causes the relation remains unclear. The central star-forming galaxies in the EAGLE cosmological numerical simulation reproduce the observed trend. We use them to explore the origin of the relation assuming that the physical mechanism responsible for the anti-correlation between size and gas-phase metallicity is the same in the simulated and the observed galaxies. We consider the three most likely causes: (1) metal-poor gas inflows feeding the star-formation process, (2) metal-rich gas outflows particularly efficient in shallow gravitational potentials, and (3) enhanced efficiency of the star-formation process in compact galaxies. Outflows (2) and enhanced star-formation efficiency (3) can be discarded. Metal-poor gas inflows (1) cause the correlation in the simulated galaxies. Galaxies grow in size with time, so those that receive gas later are both metal poorer and larger, giving rise to the observed anti-correlation. As expected within this explanation, larger galaxies have younger stellar populations. We explore the variation with redshift of the relation, which is maintained up to, at least, redshift 8.