The layers are less permanent than they look. In a latte macchiato, espresso can settle between steamed milk and its cap of foam because differences in density encourage stratification, while a gentle pour limits the turbulence that would otherwise blend the drink. The boundary is a temporary arrangement, not a wall.
Temperature helps, but it does not work alone. Heated liquids generally expand and become less dense; espresso that is hotter than the milk can therefore have an advantage in staying above it. Composition matters too. Milk contains dissolved sugars, proteins and fat, while espresso contains dissolved coffee solids, so the relative densities depend on both ingredients and their temperatures. The foam, meanwhile, contains enough trapped air to make it less dense than either liquid. Its bubbles, stabilized in part by milk proteins, give the coffee a surface beneath which it can spread.
Technique is the difference between a band and a blur. Pour espresso slowly into the prepared milk and foam, and the incoming stream has a better chance of finding a level where its density is close to that of its surroundings. Pour too forcefully and turbulence carries coffee deeper into the milk; even a careful pour produces some mixing. Heat moves as well. As the liquids exchange heat and diffuse into one another, their boundaries soften, and the layers become harder to distinguish. In the glass, order is visible precisely because it will not last.