In a magnet, the magnetic force is concentrated at the ends and gets weaker in the middle. These magnetically strong ends are called magnetic poles. Magnets have two poles, both of equal strength. The Earth also has magnetic poles. A compass works because the magnet in the compass is responding to the magnetic force of the Earth.
A simple bar magnet allowed to rotate freely will always align itself with the magnetic north and south poles of the Earth. Some magnets are marked with an N on one end and a S on the other. This is because the N end will always point north, while the S end will always point south. If two magnets are placed side by side, the N end of the first magnet will attract the S end of the second, while the N ends will repel each other.
The pull of the magnetic poles of the Earth is so strong that a magnet will always align with the poles no matter how far it is from them. It should be noted that the magnetic north pole of the Earth does not align perfectly with the geographic north pole. Magnetic north is actually about 15 degrees away from geographic north.
For thousands of years, people have been using the magnetic poles of the Earth to help them navigate. A compass is basically a freely rotating needle. Since the needle is magnetized, it will always point north. Knowing which direction is north, explorers and travelers can figure out which direction they are going. The first mention of the compass was made by the ancient Chinese around 210 BCE.
A couple of different theories exist to explain why magnets behave the way they do. The older of the two is Weber's theory. It states that magnetic substances are made of tiny magnetized molecules. When left alone, these molecules point in all different directions. If a magnet is pulled over the material multiple times moving the same direction, the molecules will line up like a series of tiny magnets north end to south end, creating magnetic poles on either end of the metal.
A similar but more sophisticated theory relies on the knowledge that electrons have a magnetic field. Electrons are the tiny units that orbit around atoms. Every atom has at least one electron. The Domain theory states that if an atom's electrons are orbiting all in different directions, their magnetic fields will cancel each other out. If, however, they are orbiting in the same direction, the atom will be magnetized. A material full of these magnetized atoms is a magnet.