Fossil fuels are formed by decomposing dead and decaying plant or animal matter underground for millions of years.
When any plant or animal dies, soil bacteria start decomposing the matter which was gradually buried by the layers of rock in the earth's crust which increases the heat and pressure inside, and as a result of heat, fossil molecules begin to break apart.
Coal, Natural gas, and oil are examples of fossil fuels that take millions of years to form.