In the earths atmosphere, pressure, which is related to the number of molecules per unit volume, decreases exponentially with altitude. Thus, if a parcel of air from the surface rises (because of wind flowing up the side of a mountain, for example), it undergoes an expansion, from higher to lower pressure. When you allow air to expand, it cools. This phenomenon is familiar to everyone--stick your finger on the valve of a car tire, and let some air escape. It is not cool inside the tire, but as the air comes out it expands and thus cools.
Michael Tinnesand, associate director for academic programs at the American Chemical Society, provides the following explanation:
The basic answer is that the farther away you get from the earth, the thinner the atmosphere gets. The total heat content of a system is directly related to the amount of matter present, so it is cooler at higher elevations.
The heating of the earth itself also plays a role. The planet is warmed by incoming solar energy. Some of this heat bounces off the atmosphere and never reaches the lower atmosphere, and some is re-radiated back to space. In addition, the atmosphere acts like a greenhouse to reflect some of the heat back toward the earth's surface. At higher altitudes it is relatively harder to retain this energy as more heat is lost to space.