Galaxies are formed through a process that involves the gravitational attraction of matter in the universe. Initially, small perturbations in the density of matter caused some regions to have slightly more matter than others. These regions then attracted more matter through gravity, eventually forming stars, galaxies, and clusters of galaxies.