Under normal conditions, air temperature decreases as altitude increases. In practice, air temperature is closely linked to that of the ground: in contact with the ground the air warms up and, becoming lighter, tends to rise.
During this upward phase the same mass of air expands, because atmospheric pressure decreases as altitude increases, and as it expands its temperature tends to drop.
Let's say that normally (with the air at rest), temperature decreases by about 6 degrees every 1000 metres of altitude (which, in theory, means that if it were 20° at sea level, at
4000 m we would be at -4°). In reality it can happen that air temperature increases with altitude: this is the case of temperature inversions.
Temperature inversions can occur at ground level but also at altitude.
Ground inversions occur, for example, in winter on valley floors and at low altitude, usually up to 1000 m, rarely higher: the ground may be covered by a layer of snow that prevents the sun from warming the ground itself, or in any case the long cold nights allow only limited warming of the ground during daylight hours, or else the shade of a wood stops the morning sunshine from warming the ground. It often happens on high-pressure nights with very little wind: in these cases the air in contact with the ground cools very quickly, reaching lower temperatures than the layers above: this is how fog forms.
In upper-air inversions, on the other hand, warm air slides over a layer of colder air. In practice the colder air is able to rise until it meets the layer of warm air: no longer able to expand vertically, it spreads out sideways. This phenomenon is easy to recognise from the formation of "anvil"-shaped clouds, which then give rise to thunderstorms.
Obviously, above the warmer layer, the air behaves as under normal conditions, where temperature drops as altitude increases.