When air is compressed the volume decreases. This happens because the molecules at vast distances come together, resulting in an increase in kinetic energy, and as a consequence an increase in temperature. Also, the pressure increases, when the air is compressed.
The air closer to the surface of the earth is denser as it has to carry the weight of the air above it. Also, the heated and expanded air rises above as it is lighter and cannot bear the weight of the denser air above it. So the air near the earth's surface is denser.