There are a few different methods, but one of the most common is the ‘standard candle’ method. This relies on the fact that if we know how bright an object in space really is (its ‘intrinsic’ brightness), then we can estimate its distance from how bright it appears to us from Earth (its ‘apparent’ brightness).
A ‘Cepheid variable’ is one type of standard candle. Cepheid variables are a type of star that have a consistent relationship between their intrinsic brightness and how fast they pulsate – so you can watch one, and if it pulsates at x speed, you know its intrinsic brightness is y.
Measuring the intrinsic brightness of a Cepheid variable, or other kinds of standard candles such as supernovae, allows astronomers to calculate the distance to the standard candle’s home galaxy.
For the most distant galaxies, standard candles are too faint to be useful, so astronomers often use the ‘Hubble-Lemaître’ law, which shows that the further a galaxy is from Earth, the faster it is moving away from us. This is just a consequence of the fact that the Universe is expanding.
Astronomers first measure the speed of the galaxy by analysing the shift in the galaxy’s light towards the red end of its light spectrum (its ‘redshift’), and once its speed is known, they can work out its distance.