It's a consequence of the "clumpiness" of the early universe. There were vast areas with very slight concentrations of mass, and vast areas with very slightly lower densities of mass. Self-gravity of the denser regions caused them to condense into proto-galaxies - and conservation of angular momentum played a role in shaping them. Smaller proto-galaxies were often accreted/cannibalised by larger ones in their vicinity, but sufficiently isolated galaxies were preserved in this gravitational dance; this produced a distribution of galaxy sizes and morphological types.
[The same basic physics also played out on a much smaller scale within the proto-galaxies, where density enhancements in gas clouds led to the formation of the first population of stars].