The answer is equally intuitive as it is fascinating- as the California weather heats up, a low-pressure atmosphere is created due to heat rising. This in turn invites in cold air from the city's surrounding Pacific Ocean that gets sucked in through the easiest access point- our Golden Gate.
Air always wants to move from areas of high pressure to low. Our ideal low-pressure zone acts as a powerful vacuum to siphon in this moist seawater air that condenses from the heat, an
upwelling that creates Karl and the famous
marine layer that remains due to this temperature inversion.
A temperature inversion is when the air continues to warm as it rises, which is the complete opposite of what normally happens.
San Francisco's prime location by the water, its terrain, elevation, and pressure gradients all interact to enact this intriguing anomaly, with the warm air above keeping the cold marine layer and fog (specifically
advection fog) below trapped, like a lid over the city.