Air cools when it rises through the atmosphere because as altitude increases, air pressure decreases and allows the individual air molecules to expand away from each other. This expansion leads to a decrease in collisions between air molecules, which then results in less heat energy being transferred between those molecules.
At the Earth's surface, air pressure is greatest due to the combined weight of all the air molecules in the atmosphere above. Once an air mass is heated, it rises into the atmosphere. During this ascent, the heat energy of the air mass is gradually used to expand the air mass. This accounts for the loss of heat as air rises through the atmosphere.