Well this is not a question that can be answered in a few sentences!
In short
We still do not know, how exactly the galaxies formed and have the shapes they possess. The large-scale structure (LSS) in the Universe as we see them today are a consequence of tiny primordial density fluctuations that arose right after the
Big Bang.
The reason for these tiny density fluctuations is believed to be quantum in nature.
So, these tiny fluctuations in the early past lead to agglomeration of gas and dust clouds, leading to certain areas becoming denser. These denser areas slowed down the expansion of the Universe, allowing the gas to accumalate into small protogalactic clouds. Gravity in these clouds casued the gas and dust to collapse, and in turn form stars. These stars burned quickly and became globular clusters (while gravity was still collapsing the dust and gas).
Also, according to the $\Lambda$CDM model, the structures form in a "bottom-up" fashion, i.e. small structures forming first (stars and galaxies) followed by large structures (galaxy clusters). This is exactly what we are observing today thanks to surveys that are probing high redshift ranges.