Oil and gas both form when organic matter is buried under anoxic conditions, such that it isn't oxidised and subsequently mineralised to the elemental components of the hydrocarbons.
What hydrocarbons are formed depends on both burial depth and temperature. Above approximately 1km below the surface no significant formation of oil takes place, and hydrocarbons are either mineralised or broken down to volatile products such as methane, propane, and butane.
The often so called 'oil window' is located below 1km, but above ~4km, and at temperatures between 40-50 °C and 150 °C. Under these conditions long hydrocarbon chains can form without being broken down to shorter, more volatile chains.
At larger depths or higher temperatures no (significant amount of) oil is formed, and all organic matter is transformed to natural gas.

An approximate graph after Nichols (2009).
Formation of these fossil fuels often takes place in shales (lithified clay) that are rich in organic matter, but as all sedimentary rocks this is a porous medium and thus liquids will tend to flow upwards to areas of lower pressure. To be preserved two other components are therefore necessary: a reservoir rock (often sandstone) and a sealing rock (numerous types of rock are suitable, including rock salt and certain igneous rocks), often in dome or fault structures.
Source: Nichols, Gary (2009) Sedimentology and Stratigraphy, p 293-295