Early on, the universe was filled with hydrogen and helium. Some areas that were more dense slowed the expansion of the universe. This caused hydrogen and helium to accumulate into small clouds. The gas in these clouds collapsed due to gravity and the first generation of stars was formed. These stars rapidly burned out.
Clouds continued to form and collapse due to gravity. As these clouds neared each other, gravity caused them to hurtle into each other and become larger, spinning packs. Then, when the clouds collapsed they became rotating discs that created more gas and dust. New stars formed in arms and colonies.
Thus, a galaxy was formed as a cluster of stars with a halo of gas, dust, and dark matter.