When the solar system formed it began as a cloud of gas and dust. As the sun condensed out of the cloud the remaining gas and dust was drawn into orbit around it, forming a disk. Over time, larger rocks and pebbles in the disk accumulated the material around them during their orbit of the forming sun, like rolling snowballs getting larger and larger.
At some point during the formation of the sun, enough pressure builds up inside to allow ignition of its fusion fuel (mostly hydrogen). As the sun heats up it begins emitting radiation and the ejection of particles (solar wind). It’s this combination of stuff (light and particles) that pushes lighter gases out of the near orbital region (where the rocky planets formed). Those gases make their way out beyond the asteroid belt and get picked up by the forming gas giants. At the same time, the heavier dust and rocks don’t get pushed very far by the sun and instead get accumulated in the rocky inner planets.
This pattern is more or less consistent around all stars we see out there. Of course, it varies in strength based on the amount of radiation and particles emitted by the star and that is a complex topic all by itself. But I hope the basic picture I’ve given here is informative.