Specific gasses have very specific absorption line patterns making their presence very easy to detect. If the object, and indeed the observer, was stationary then the absorption lines will be in their rightful, predicted place in the spectrum, but if they are moving relative to each other, then the absorption lines become shifted.
If the distance between the objects is increasing, then the lines will have moved toward the red end of the spectrum (red-shifted) and if the distance was decreasing then the lines would be moving toward the blue end (blue-shifted).
However, most stars and galaxies are red-shifted from our perspective. The mechanism that makes this happen is related to the way the Universe is expanding. When the light was emitted, the absorption lines were in their rightful place in the spectrum, but by the time the light got to the observer, the Universe had expanded, and the spectrum of the light had shifted.
By measuring the amount of red-shifting, it's possible to calculate how fast the galaxies are moving apart and also how far away they are. The formula for this is pretty tried and tested, unfortunately it relies on one of sciences only variable constant, the Hubble Constant. We are narrowing down the exact value of this but until then, the distant estimates using this technique are often have some big error margins!