Answer:
Becuse magnesium is a earth alkaline metal and oxygen is a nonmetal(read explanation)
Step-by-step explanation:
Magnesium has 2 valence electrons where oxygen has 6 valence electrons. Magnesium has tendency to give electrons to oxygen and oxygen has tendency to gain electrons. They are both trying to complete their last shell to 8 which is called the octet rule. Because they both want to complete each other because of the reasons that I told they combine to be stanle atoms like noble gases.