Here's how it works:
1. Gravitational Collapse: A giant cloud of gas and dust (a nebula) collapses under its own gravity.
2. Conservation of Angular Momentum: As the cloud collapses, it spins faster, much like an ice skater pulling their arms in. This spinning creates a flat, rotating disk.
3. Planetesimal Formation: Within this disk, dust and gas particles collide and stick together, forming larger and larger clumps called planetesimals.
4. Planetary Formation: These planetesimals continue to collide and accrete, eventually forming planets.
Because the planets formed from the same rotating disk, they all orbit in the same direction (prograde) and on approximately the same plane (the ecliptic plane).
This is similar to a spinning pizza dough; as the dough spins, the toppings (like the planets) are flung outwards and end up distributed on the same plane.