In an electromagnetic train, they use electromagnets to attract each other to lift up the train as shown below. My question is, how do they make it levitate? It seems like the electromagnets will just be attracted to each other and therefore stick to each other which causes it to be stuck in the rails.
You are correct. Without an active feedback mechanism that senses the distance between the train and the track the two would stick together just like ordinary magnets. There is even a mathematical proof for that called Earnshaw's theorem, which applies to both point charges and magnetic materials. The theorem rules out any static configuration of charges and magnets that would maintain stable levitation. There are exceptions in the theorem for diamagnetic materials that will allow for levitation of small objects in strong fields and levitation using superconductors. It also doesn't forbid the levitation of moving objects (like spinning magnetic tops) and configurations with AC fields. In practice, however, most engineering designs will also employ active regulation of the distance between the tracks and the trains by changing the strength of the magnetic field.
Complete physics of levitating train is nicely animated and explained in this film: https://www.youtube.com/watch?v=XjwF-STGtfE There are various films on the Internet, but for me the description is clearest in every aspect of the described physics. I hope you'll find it useful, especially in visualizing the problem.
I don't consider this an answer, but since I cannot make comments yet, I write it here.