The Periodic Table is split by a stepped line. Metals are on the left and in the centre. Non-metals are on the right and at the top. An element's position tells you about the electrons in its atoms, and that explains whether it is a metal or a non-metal.
Metal atoms have few outer electrons, usually one, two or three. They lose these electrons to reach a full outer shell, which makes them form positive ions. Magnesium is in Group 2. Its atoms have 2 outer electrons, lose both, and form Mg2+ ions.
Non-metal atoms have four to seven outer electrons. They gain electrons, or share them, to reach a full outer shell. Oxygen is in Group 6. Its atoms have 6 outer electrons, gain 2 electrons and form O2- ions. A non-metal atom that gains electrons forms a negative ion. Atoms of the noble gases in Group 0 already have a full outer shell, so they do not need to gain or lose electrons.