Sunlight is already a rainbow
Sunlight looks white, but that white is a mixture. Pass it through a glass prism and it separates into a rainbow: red, orange, yellow, green, blue, violet. Each color corresponds to a different wavelength of light: red is long (about 650 nanometers), blue is shorter (about 450 nm), violet shorter still.
All these colors leave the Sun together. What turns the sky blue is how the atmosphere treats them on the way down.
Air molecules grab the blue more readily
Air is made of billions of tiny molecules: nitrogen, oxygen, a little of everything else. They are far smaller than the wavelengths of visible light. And for reasons Lord Rayleigh worked out in 1871, these molecules scatter light more efficiently the shorter its wavelength.
Blue light, as a result, is scattered about ten times more than red. Instead of travelling straight through like red, it bounces from molecule to molecule and reaches your eyes from every part of the sky at once. When you look up, what you see isn’t a slice of the Sun. It’s the blue light that zigzagged through the atmosphere and now arrives from everywhere.
(Why not violet, then, which is shorter still? Because the Sun emits less violet than blue, and our eyes are less sensitive to it. The mix tilts toward pure blue.)
At sunset, the blue takes its leave
When the Sun is high overhead, its light passes through relatively little atmosphere. At sunset it reaches us almost horizontally, after travelling through hundreds of kilometres of air. Along that long path, all the blue light ends up scattered sideways, until none is left.
Only the long wavelengths, red and orange, pass through in a straight line. That filtered light is what paints the sunset.
The spectacle changes elsewhere. On the Moon, which has no atmosphere, the sky stays black even at noon: nothing to scatter anything. On Mars, where the air is thin and laden with rusty dust, the daytime sky leans butterscotch. The blue of Earth’s sky is a signature of our particular atmosphere — nothing more, nothing less.