This happens because our visual system try its best to infer the innate properties (brightness, color, etc.) of the objects we see. For instance, we perceive the 'true' color of an object regardless of the lighting condition. Also, our visual system processes 'difference' much better than 'absolute value'. Therefore, perceived lightness highly depends on the lightness of the surrounding.
When two areas with different lightness meet, the lightness different at the interface dominates our perception. Below, the left side looks darker even though they are the same shade of gray.
It become clear if we block the interface.
The shaded diamonds illusion clearly demonstrates this effect.
Psychophysics is a discipline that studies the quantitative relationships between stimuli and perception. There are several 'laws' of Psychophysics. Weber-Fechner's law notes that the JND (just noticeable difference) between two stimuli is proportional to the size of the stimuli. For instance. Stevens' power law tells that the perceived strength (\(S\)) of a stimulus (\(I\)) scales as a power-law (\(S = kI^{\alpha}\)).
Although these laws are not as robust as the laws of Physics, it is important to know about them. For instance, it is a very important lesson that we perceive length much more accurately than area or volume.