The main force is gravity, but magnetism also plays a secondary role in keeping the atmosphere on Earth. Specifically, gravity is what holds the majority of the atmosphere down, but magnetism prevents the upper parts of the atmosphere from being scavenged away by the solar winds.
What type of an atmosphere a planet has, is very dependent on how much gravity it has, and thus how much that planet weighs. A planet like Earth doesn't have enough gravity to hang onto hydrogen or helium gas, the two lightest gases in the universe, it can only hold down denser forms of gas that are molecular in nature. What hydrogen Earth still has, has to be locked into more complex heavier molecules attached to either carbon or oxygen atoms, for example, water (H2O) or methane (CH4). But much heavier planets, such as the gas giants (Uranus, Neptune, Saturn & Jupiter) have enough gravity to hold onto their hydrogen and helium too. This is all courtesy of gravity.
The smaller and smaller a planet is, the less and less it can hold onto its atmosphere, the lightest gases are the ones that disappear first. However, the magnetic field of the planet plays a secondary role in retaining that atmosphere. The magnetic field is used to divert solar wind particles (which are charged plasma) from crashing into the atmospheres of the planets and it safely diverts them around the planet. Due to the solar wind, planets like Venus (lack of magnetic field), and Mars (lack of gravity and magnetic field) have a much worse atmosphere than Earth.
You could say that Earth has a Goldilocks atmosphere. It's not massive enough to retain free hydrogen or helium, which would overwhelm the rest of the gases in an atmosphere, making it difficult for life as we know it to emerge. But it is massive enough to retain all of these other gases. And it's got a magnetic field strong enough to protect the atmosphere from solar wind bombardment.