For a fossil to form, the remains of an animal need to be covered with sediment relatively quickly after the organism's death. The soft tissues rot away before the sediment hardens around the bones and teeth. Eventually, the remains dissolve, leaving a gap in the rock that fills with minerals.
A variety of different substances can offer the right conditions for fossilization. Moist peat bogs are excellent for preserving fossils, since the hard remains can sink below the surface, protected from predators and bacteria. Volcanic ash is another good preservative for fossils. The ocean is an excellent source of fossil preservation, with constantly renewed layers of sediment to bury remains and start the fossilization process. Many of the world's best fossil fields were once covered by ocean waters.
Once the remains are buried, the sediment has to have a chance to solidify to preserve a cast of the bones. This usually occurs when pressure works on the layers over time. The seal around the remains is rarely complete, however, allowing the original bones to dissolve away over time. Cracks in the sediment layers then allow mineral-rich water to flow into the negative space, creating a replica of the original remains out of stone.