The planets, asteroids and comets in the solar system are loose objects left over from the formation of the Sun. Originally the gas and dust that would become the Sun was the core of a cloud much larger than the solar system, probably several light-years across. (One light-year is equal to approximately 6,000,000,000,000 miles.) The core was slowly rotating at first, but as it collapsed it spun faster, like a spinning ice-skater pulling in his arms. The rotation prevented the material at the core's equator from collapsing as fast as material at the poles, so the core became a spinning disk.
Gas and dust in the disc spiraled gradually in to the center, where it accumulated to form the Sun. But because dust is denser than gas, some of the dust settled to the mid-plane of the disc. These dust particles stuck together to make clumps, then clumps stuck together to make rocks, then rocks collided to make planets. In the case of the "gas giant" planets, Jupiter, Saturn, Uranus and Neptune, the rocky cores were massive enough to also attract some of the gas. The outer layers of these planets are made up of hydrogen and other gases.
So the Sun is the collapsed core of an interstellar gas cloud, and the planets, asteroids and comets are small lumps of dust or ice chunks which stayed in orbit instead of spiraling into the Sun. The planets all formed within a very short period, probably a few million years, about five billion years ago.
HubbleSite and STScI are not responsible for content found outside of hubblesite.org and stsci.edu