Why is shaving cream foamy?

If we blow air into soapy water, the soap molecules will quickly arrange themselves so that the fatty end is in the air bubble, so the sodium end can stay in the water. The bubble rises, and meets the layer of soap at the top surface of the water. This surface has all of the fatty ends of the soap sticking up into the air.

As the bubble rises up, we now have two soap surfaces, one with the fatty ends of the soap facing the air outside, and another with its fatty ends facing the air inside the bubble. The sodium ends of the soap hold onto the very thin layer of water between the two soap film surfaces. This is what soap bubbles are made of.

Shaving cream used to be made by mixing soap and water together using a shaving brush. The many bristles of the brush act like a whisk to make lots of tiny bubbles.

Shaving cream in a can is a mixture of oils and soaps combined with a propellant made from propane or butane. The gas is under pressure (so much pressure that the butane is a liquid in the can). When the user pushes the button on the can, the pressure forces out the soap, and the gas expands into bubbles. The tiny bubbles are so small and numerous that they form a stiff lather.