The primary reason objects float is buoyancy, an effect discovered by Archimedes of Syracuse. Basically, this principle states an object will float if it weighs the same as the amount of water it displaces. In other words, a 20 lb. object will float if it displaces 20 lbs. of water. The object also does not have to be in water; it’s just easier to imagine a boat in water than a ball bearing in heavy oil. The principle, though, is the same in both cases.
Normally, when the word “float” is used, the phrase “on top of” is implied immediately after it, but this does not have to be the case with Archimedes Principle. A submarine operates off of this principle, even though it “floats” while completely submerged. It is always displacing the same volume of water, so when it releases its ballast tanks, which reduces its weight, it rises.
This can get a little complicated the deeper the submarine dives because Archimedes Principle is based on the weight of the water displaced, not the volume. At lower depths, water is more dense, which means the same volume of water weighs more. In other words, the lower you go in depth, the greater the buoyant force. A similar principle applies to the atmosphere. Objects that float in air displace the same volume as they get higher, but because the atmosphere becomes less dense at altitude, the weight of the air that’s displaced is lower.
Sometimes, things float without displacing anything. Put water, oil, and vinegar in a bottle, shake them together, and then wait awhile. Eventually they will settle into layers. This stratification is the product of Archimedes Principle and another force called “surface tension.” When the bottle is shaken, droplets of each fluid become mixed with the others. Buoyant forces cause them to separate into the layers that you see, but there is a force across the boundaries of the fluids preventing them from remixing unless they are shaken again. This is surface tension.
Some water insects take advantage of this surface tension. They typically have long skinny legs that are spread far apart compared to their bodies. Neither of their legs carries enough weight to break through the surface tension of the water. The result is they have the ability to literally walk on water.
Objects float as a result of their own weight, the weight of the fluid they displace, and the effect surface tension has on them. Oil on vinegar, ships at sea, and bugs on water all obey the same laws of physics.