While a lot of details about how galaxies formed are unclear, and different researchers have different emphases and perspectives (sometimes very different), the general idea is as follows (much detail omitted; caveats apply!):
- at the time of matter-radiation decoupling (when electrons combined with protons to form hydrogen atoms, ~the surface of last scattering, which we now see as the CMB), some regions of the universe were slightly denser than others, and some were slightly less dense (how this came about is another story)
- ('density' here means density of mass, which is predominantly 'dark matter'; ordinary matter - 'baryonic matter' - is a minor constituent)
- the 'overdense' parts would attract more matter, and shrink
- the baryonic matter part of these blobs would shrink to gas clouds; the dark matter part wouldn't shrink
- parts of the gas clouds embedded in dark matter blobs would contract and collapse to form massive stars
- these collections of massive stars in gas clouds in dark matter blobs are 'protogalaxies', and several examples may have recently been observed
- the massive stars would evolve very quickly, become supernovae, and collapse to black holes
- some black holes would merge, and form the seed for galaxy nuclei
- protogalaxies would collide and merge, to form galaxies
- the expansion of the universe was not great enough to pull the gas clouds and protogalaxies apart (or, gravity was stronger than the universal expansion)
- as the overdensity regions were of many different sizes, so some galaxies were able to form clusters, and some clusters to form super-clusters (being larger, these took longer to form than the proto-galaxies!)
[Edit: fixed typo

]