When altitude increases, air temperature decreases. This is because, with an increase in altitude, there is a decrease in air pressure. When air pressure decreases, air cools down.
The density of air molecules is greatest near the surface and thins out as the altitude increases. One of the main reasons for a higher density of air molecules closer to the Earth's surface is gravity. The force of gravity decreases at distances further away from Earth's surface, so the planet's hold on the air molecules is greatest at lower altitudes. A higher density of air molecules implies higher air pressure. According to Gay-Lussac's law, the pressure of gases is directly proportional to the temperature of the gases for a constant volume. Higher pressure at a lower altitude therefore implies higher temperature. When the air pressure decreases with altitude, so does the temperature.
Another factor that contributes to the temperature difference based on altitude is the greenhouse effect. When sunlight falls on the Earth's surface, a portion of its heat is absorbed by the gas molecules in the surroundings. A higher number of gas molecules implies a greater quantity of heat being absorbed. Since the density of gas molecules is greater at low altitudes, more heat is absorbed and retained by the greenhouse gases compared to at higher altitudes. This makes the air warmer closer to the Earth's surface.