I’m seeing a lot of replies that say “CO2 /methane trap heat” without saying why – but I think OP’s question is actually asking *how* greenhouse gases trap heat, which is an excellent question but also involves some difficult concepts.
CO2 traps heat because the molecule O=C=O absorbs Infrared (IR) light due to a match in what we call a “bend” of the molecule. This bend just happens to be at the right kind of energy. This IR light is a lot of what the earth is producing from its surface, so it’s the most important light to trap if you want to trap heat. If CO2 is able to absorb this heat, then the heat remains “on” earth (in the atmosphere’s CO2) and since stopping something getting cold is very closely related to keeping something warm – we say that CO2 has a “warming” effect (or a greenhouse effect).
In fact, anything that can absorb IR heat energy is a greenhouse gas. A *lot* of things absorb IR heat. The question is how well the molecule is suited to absorbing a lot of IR heat.
Methane traps heat very well because of the nature of its C-H bonds. Explaining why molecules absorb certain frequencies of light is degree-level chemistry, but a simple explanation is that because H is a very “small” molecule (it is physically light and easy to move around) this means that absorption in what we call overtone stretches become much more common, and the number of different overtones each variation of methane vibrations is massive. A lot of possible matches = much more possible IR light to absorb = very broad IR spectrum = very good at absorbing heat = very good greenhouse gas.
To imagine why H acts like this, imagine yourself as Carbon. You tie a ball to a string and I will ask you to come up with as many different kinds of swirls, swinging actions and “vibrations” as possible (imagine doing a helicopter with the ball as being just one possible action).
Now, if the ball I give you is very small (e.g. tennis ball), you will be able to more easily come up with different swirls, tricks and patterns compared to if I gave you a huge, heavy ball. Understanding this means you can understand why Carbon can achieve more tonal vibrations with “small” Hydrogen compared to “large” oxygen. And if we can produce more vibrations, we can absorb more heat in the IR spectrum.
If you can understand that, congratulations – you just did about 1/8 of a module in degree level chemistry.
Edit: to add some clarification to the above. H = Hydrogen. O = Oxygen. C= Carbon. I realise I interchange between these a lot.