Typically, the temperateure decreases as we go up for the 10-20 km. However, at some height the air may actually get warmer for just a little while. This is called an inversion. Inversion can occur at almost any altitude. Clouds usually form near an inversion.
Scientists believe our atmosphere was formed when gases seeped out of the Earth.
There were large amounts of water vapor that became lakes. Nitrogen and carbon dioxide also leaked out of the Earth. These gases were unable to escape the Earth's gravitational pull. Eventually, there was enough gas to create an atmosphere. This is a simple question of density.