Sunlight looks white but contains every color in the visible spectrum. When it enters Earth’s atmosphere, it collides with nitrogen and oxygen molecules, and those collisions scatter the light. The shorter the wavelength of light, the more it scatters. Violet scatters more than blue, blue scatters more than green, green more than yellow, yellow more than red. This process is called Rayleigh scattering, named for the British physicist Lord Rayleigh who worked out the mathematics in the 1870s.
Because blue light scatters in all directions across the entire sky, you see blue coming from everywhere overhead, not just from the direction of the sun. Red light mostly travels straight through and arrives at your eyes directly from the solar disk, which is why the sun looks yellowish rather than white.
At sunset, the sun sits at a low angle, and its light has to pass through a much longer slice of atmosphere to reach you. By the time it arrives, most of the blue has scattered away. What remains is the long-wavelength end of the spectrum: orange and red. The sky at sunset is the blue sky turned inside out. You are seeing what’s left over after the blue is gone.
Here is the part people usually leave out: violet light scatters even more than blue. If Rayleigh scattering were the whole story, the sky should look violet, not blue.
The reason it doesn’t comes down to three overlapping factors. First, sunlight contains less violet than blue to begin with. The sun’s output peaks in the green-yellow range, and there is simply less violet in the incoming light to scatter. Second, the upper atmosphere absorbs some violet before it reaches lower altitudes. Third, and most interestingly, human eyes are much less sensitive to violet than to blue. The photoreceptors in your retina that detect short wavelengths are called S-cones. They respond to wavelengths in the range of about 420 to 440 nanometers, which is more blue-violet than pure violet. When your visual system assembles the mix of scattered short-wavelength light reaching your eyes, it interprets it as blue.
The sky is not blue. The sky scatters violet and blue both, but human visual biology makes violet hard to see and blue easy to see, and so the sky looks blue to you. A mantis shrimp, with its 16 types of color photoreceptors including several in the ultraviolet range, presumably perceives the sky differently.
Mars has a sky that turns pink-red during its day and briefly blue at sunset, essentially the reverse of Earth, because Martian dust scatters red and orange light in the same way Earth’s atmosphere scatters blue. The planet’s thin atmosphere and iron-rich dust create the inversion. On Mars, sunsets run blue.
The basic physics is the same everywhere. What changes is the stuff in the atmosphere, and who is looking.