The attraction or repulsion between magnets is caused by their magnetic fields. A magnetic field is a region of space around a magnet where the force of magnetism is exerted. The magnetic field of a magnet is strongest near the poles of the magnet and weakest in the middle.
When the north pole of one magnet is brought near the south pole of another magnet, the two magnetic fields interact and attract each other. This is because the north pole of one magnet has a magnetic field that is opposite to the south pole of the other magnet. The opposite poles attract each other, just like positive and negative charges attract each other.
When the north pole of one magnet is brought near the north pole of another magnet, or the south pole of one magnet is brought near the south pole of another magnet, the two magnetic fields interact and repel each other. This is because the two magnetic fields are in the same direction and therefore repel each other.
The force of attraction or repulsion between two magnets depends on the strength of the magnetic fields of the magnets and the distance between the magnets. The stronger the magnetic fields and the closer the magnets are, the stronger the force of attraction or repulsion.
The exact mechanism of magnetism is not fully understood, but it is believed to be caused by the movement of electrons within the magnet. Electrons have a property called spin, and when electrons spin in the same direction, they create a magnetic field. The more electrons that are spinning in the same direction, the stronger the magnetic field.
Magnets are used in many different ways, including in compasses, refrigerator magnets, and motors. They are also used in medical devices, such as MRI machines.