Oil and gas were formed from the remains of animals and plants that lived millions of years ago in the sea. These remains were covered by layers of sand and silt. Heat and pressure from the Earth's core turned them into oil and gas. The oil and gas were trapped between layers of impermeable rocks.
Coal was formed from dead plants about 300 million years ago. Back then, much of the Earth was covered by swamps. As the vegetation died, it decayed, slowly forming layers of peat. Over time this was covered with more sediment and compressed and heated to form coal.