A star maintains equilibrium by balancing two things: the pressure of the superheated gas/plasma in the star undergoing a fusion reaction acting out away from the center and gravity acting toward the center. When a star runs out of hydrogen to fuse into helium, does the fusion reaction stop and the star collapses? No. The star shrinks due to the gravity and the lack of a fusion reaction taking place, the helium is compressed harder, and pressure & temperature goes up until the helium starts fusing into a heavier element. Other than the temperature and pressure required, it undergoes a fusion reaction that gives off lots of energy. When the helium runs out, the star once again shrinks in on itself until the heavier element starts a fusion reaction again. This should theoretically go on forever, right? No. The problem is that when you reach iron in the core, the fusion reaction for that element absorbs energy instead of giving it off. Iron in the core kills your star.
What happens then? You’ve got gravity acting in and nothing appreciable pushing out anymore. At that point, your star collapses at a relativistic speed, approx. 1/3 the speed of light. If your star is 1.4 times the mass of our sun or larger, it collapses into a super-tight mass under tremendous pressure. The star under tremendous pressure rebounds in a supernova explosion that, for a short time, glows brighter than the sum-total of every other star in the galaxy (we’ve spotted supernova explosions from millions of light years away, far outside the milky way). That relativistic collapse and the material that is blown off in the explosion is where we get our heavy elements such as gold, uranium, lead, and other heavy stuff. The material that is retained by the tremendous gravity is incredibly dense and forms your neutron star or black hole depending on the mass of your original star. Our sun does this with more of a whimper and will be a white dwarf. 1.4-3.3 solar masses will get you a supernova explosion and form a neutron star. 3.3 solar masses or larger gets you a black hole.
Now to your question:
Gravity is based on the mass but also on the density. Think of the mass of the milky way: 200+ billion times our sun but it’s not a mondo super black hole because it’s so spread out. You gotta crunch mass down to get a neutron star or black hole. When your star forms iron in the core and collapses at 1/3 the speed of light, that’s where you get that big crunch and those super high densities. It doesn’t gain mass, in fact it loses mass because it ejects heavy elements. But what it does gain is DENSITY.