In the protostar stage of the Sun, it was surrounded by a (spinning) gas cloud. This cloud behaved like a fluid (well, a gas is a fluid), so it flattened out into an accretion disk due to conservation of angular momentum. The planets eventually formed from the dust/gas in the disk from compression of the dust in the disk. This process won't end up moving the dust out of the plane (all the vertical force of gravity is toward the disk), so the final planet is in the plane too.
Why does an accretion disk have to be flat? Well, firstly, let's imagine the protostar and gas cloud before the accretion disk formed. Usually such a setup will have particles spinning in mostly one direction. The ones spinning in retrograde orbits will end up reversing themselves due to collisions.
In this gas sphere, there will be an equal number of particles with positive and negative vertical velocities (at a given point in time; due to rotation the velocity signs will flip). From collisions, eventually these will all become zero.
A particle revolving around a planet will always revolve such that the projection on the planet is a great circle. Thus we cannot have a particle with vertical velocity zero but with vertical position nonzero (as that would imply an orbit that isn't a great circle). So as the vertical velocity decreases, the orbit inclination decreases too. Eventually leading to an accretion disk with very little vertical spread.