* Formation: The density of a planet is primarily determined by its composition and how it formed. Planets closer to the sun tend to be rocky (like Earth, Mercury, Venus, and Mars) because the intense heat and solar wind pushed lighter elements like hydrogen and helium further out. Planets further out, like Jupiter and Saturn, are mostly composed of gas, which is less dense.
* Exceptions: There are exceptions. While the inner planets are generally denser than the outer gas giants, there are some variations. Uranus and Neptune, for example, are considered "ice giants" and have a higher density than the gas giants due to their icy composition.
In summary: While a planet's distance from the sun does play a role in its initial composition, it doesn't determine its density. The density is ultimately a function of what the planet is made of.