Answer:
This is one of the questions we still don't have a conclusive answer to, but as scientists search the cosmos for clues, the mystery becomes clearer.
Galaxies probably began to form less than a billion years after the Big Bang, which occurred around 13.7 billion years ago. The primordial Universe consisted almost entirely of hydrogen and helium gas, as well as dark matter, and was, for a time, almost completely homogeneous. It is believed that hypothetical dark matter played a major role in the formation of galaxies and the advent of a heterogeneous Universe. Clouds of gas first began clumping together due to the accumulation of primordial fluctuations, which were small changes of the density in certain parts of the early Universe. Through gravity, gas and dark matter were drawn towards the denser regions of the Universe.
There are two main hypotheses on how galaxies began to form, both of which are based on the gravitational effects of collapsing gas. One is called the "bottom-up" theory, in which giant clouds of gas came together in small clumps, which then merged to form larger galaxies. The second theory is the "top-down" one, in which clouds of gas the size of multiple galaxies broke down into individual clumps. This theory would explain why galaxies occur in clusters, and is the most widely accepted model.
Hydrogen and helium gas were then drawn towards the inner part of protogalaxies while dark matter formed a halo surrounding the outer part. The gas within these infant galaxies also began to clump together and heat up, forming the first stars. In the beginning, matter in the Universe was composed almost exclusively of hydrogen and helium. Nuclear fusion within stars (and during supernovae) would help make the rest of the heavier elements.
There are two main types of galaxies: spiral and elliptical. It is believed that spiral galaxies form as a result of dark matter (which mostly surrounds the outside of galaxies) flattening them into thin, rapidly rotating disks. Elliptical galaxies, the largest and oldest galaxies in the Universe, usually form as a result of the merging of smaller galaxies. When the Milky Way and Andromeda galaxy collide in a few billion years, it is believed that they will slowly merge to become one giant elliptical galaxy.
While scientists have learned a great deal about our galaxy and other galaxies in the Universe, the questions regarding their formation and evolution remain only tentatively answered as much research remains to be done.
See the links below for more comprehensive explanations.
Galaxies are probably formed from a gigantic cloud of gas that begins to collapse and rotate due to the force of gravity. This rotating gas cloud is where stars form, and eventually a galaxy takes shape.