Edwin Hubble discovered the universe was expanding by measuring the light of distant stars, and by showing that those distant stars were moving further away from the earth. If this is so, then why is the Andromeda Galaxy moving closer to us?
Andromeda is being pulled apart by the expanding universe. But the gravity between the Milky Way and Andromeda is strong enough to overcome this expansive force.
Gravity is pretty strong at local levels... The further away a galaxy is, the faster it’s moving away from us. But Andromeda is too close (2.5 million light-years) for that.
I quote from universetoday.com ,
At a billion light-years away, the expansion of the Universe is carrying galaxies away from us at 22,000 km/s, or about 7% of the speed of light. At 100 million light-years away, that speed is only 2,200 km/s
Click on the above link to learn more.