It’s actually an excellent question, and one that puzzled even Newton and Einstein.
If every body in space has a gravitational pull on every other body, then why hasn’t the universe simply collapsed?
One of Newton’s responses (since the question had been posed to him by a Bishop), was that “God has the universe in perfect balance, so that each body perfectly offsets the other bodies that would start such a sequence, and if it gets out of balance, then God can reset it again.” But he didn’t like that answer.
Next he postulated that the universe, if infinite, has no geometric “center”, so there’s no common place for it to collapse into. But that still didn’t explain why the phenomenon doesn’t occur locally (on a galactic level, if you want to think of a galaxy as “local”).
Einstein attempted to prove that the universe is still expanding, so the effects of gravity which would lead to a series of such collapses have not had a chance to occur yet.
I believe that the current thinking in astronomy is that the unknown properties of dark matter and dark energy have a sort of repulsive effect (a form of anti-gravity, perhaps?) that both causes the (continuing) universal expansion and also prevents the “local” collapses.
My ideas on this are cloudy, I know. It’s something I never did study or think about very much. I recommend Physics of the Impossible: A Scientific Exploration into the World of Phasers, Force Fields, Teleportation, and Time Travel by Michio Kaku, which I also didn’t understand, but which got me thinking about such things.