In the geologic past, the earth had dense forests.
Due to flooding, these forests were buried under soil
More and more soil deposited over them, they were compressed
The temperature rose as they sank deeper and deeper, Mud or acidic water protected the plants from biodegradation and oxidation, this trapped carbon in immense heat bogs that eventually covered and deeply buried by sediments.
Under high pressure and high temperature, dead vegetation slowly converted to coal.