Starlight travels through the Earth's atmosphere before reaching our eyes. The atmosphere is composed of layers with different densities and temperatures, causing the refractive index to vary continuously. As starlight passes through these varying layers, it is refracted or bent slightly in different directions. This continuous change in the path of light causes fluctuations in the apparent brightness and position of the star, leading to the twinkling effect.