The Earth's atmosphere is an extremely thin sheet of air extending from the surface of the Earth to the edge of space. If the Earth were the size of a basketball, a tightly held pillowcase would represent the thickness of the atmosphere.
Gravity holds the atmosphere to the Earth's surface.
And within the atmosphere, very complex chemical, thermodynamic , and fluid dynamics effects occur. These variations extend upward from the surface of the Earth. The sun heats the surface of the Earth, and some of this heat goes into heating the air near the surface. The heated air is then diffused or convected up through the atmosphere. Thus the air temperature will be highest near the surface and decreases as altitude increases.