Density depends on how many particles, and so how much mass, are packed into each cubic metre. In a solid and a liquid the particles are touching. There are many particles in each cubic metre, so solids and liquids have a high density. In a gas the particles are far apart. There are far fewer particles in each cubic metre, so a gas has a much lower density. For example, air is about 1.2 kg/m3 but water is 1000 kg/m3.
A solid is usually slightly denser than the same substance as a liquid, because the particles in the regular solid pattern are packed a little closer. Water is an unusual exception. Ice is less dense than liquid water, so ice floats.
When a substance changes state the number of particles does not change, so the mass stays the same. Only the volume changes. When a liquid becomes a gas the same mass spreads out over a much larger volume, so the density falls. In the same way, if a gas is squeezed into a smaller volume its mass is unchanged but its particles are closer together, so its density increases.