Quoth the Insane Clown Posse, “Water, fire, air and dirt / F**king magnets, how do they work?” Good question! Here’s the answer.
Technically, a magnet is any object that has a magnetic field. Magnetic fields are generated by the movement of electrons. All matter contains atoms, right? Well, atoms possess electrons that move in a specific orbit and have a specific spin. That motion creates an itsy-bitsy electronic field. Thing is, the majority of atoms have electrons that exist in pairs and travel in opposing directions, which means the two fields cancel each other out. That's why most things aren't magnets.
In contrast, materials that are magnetic have electrons that don't possess a pair, so the magnetic field isn't canceled out. Materials that are dense in these partnerless electrons that are spinning the same way create a larger, unified magnetic field. That material becomes a magnet and it will be especially attracted to other materials with electrons spinning in the opposite direction. It will also repel materials with electrons moving in the same direction.
"Opposites attract," said Paula Abdul, the greatest scientist in the history of the world. Magnets are attracted to (or repelled by, depending on their charge) objects made of materials such as iron, steel, nickel, and cobalt, as any of these materials can be made into magnets. Things can be magnetised, and they can be demagnetised, too. You can magnetise one of the aforementioned materials by exposing it to the magnetism of another object. The magnetism will hold especially well if the metal is superheated while it's being exposed. That's how commercial magnets are typically made.
So, that's how magnets work. It's just a bunch of lonely electrons looking for a partner to dance with. Kinda breaks your heart, doesn't it?
Oh, wait, I just looked at the next line in the ICP song, "And I don't wanna talk to a scientist / Y'all motherfuckers lying, and getting me pissed." Oh, great, that's all I need, a bunch of pissed off Juggalos and Juggalettes coming after me. I swear I'm not a scientist! I'm just a guy who kinda, sorta remembers some stuff from high school. Scientists: speak up in the comments and correct my short-comings (and let the Juggalos come after you instead).