How does Altitude Affect Temperature?

Basically, the higher that you go the lower the temperature will get. This really doesn’t make sense to me because you would think that the higher you go the closer to the sun you would get therefore temperatures should increase, but the fact that mountains keep snow on their peaks all year long proves me wrong.