Shaving cream is basically made of soap and water.
It is put into the can along with compressed butane gas.
Without the gas, all you have is soapy liquid. When the valve is pressed, some of the gas mixes with the soap and water, escapes and expands to make foam.
The filling process is just like filling a tire, or even a balloon.
As long as the pressure is maintained in a closed system and the gas from a pressurized source is not allowed to escape, it takes up a very small space.
The fact that any pressurized gas expands when the pressure is released means that a very little soap and water can make a lot of foamy bubbles.