Shaving cream is basically soap and water. It is put into a 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 that used to fill air in the tube of a tire, or even a balloon.
As long as the pressure is maintained in a closed system and the gas from a pressurised source is not allowed to escape, it takes up a very small amount of space.
The fact that any pressurised gas expands when the pressure is released means that a small quantity of soap and water can make a whole lot of foamy bubbles.