Pour cooking oil into water and the two liquids separate.
The oil usually ends up on top.
Two things are happening at the same time.
Oil and water do not mix well
Water molecules strongly attract one another.
Oil molecules interact differently.
Because of those molecular differences, the two liquids tend to separate into layers rather than blending evenly.
That is why salad dressing separates again after it sits.
Oil is usually less dense
Density describes how much mass is packed into a given volume.
Most cooking oils are less dense than water.
When the two liquids separate, the less-dense oil rises above the denser water.
What happens when you shake them?
Shaking can break the oil into tiny droplets and spread them through the water.
For a while, the mixture may look cloudy and uniform.
But the droplets are still oil.
Without something to stabilize them, they eventually collide, join together, and form a separate layer again.
Can soap help oil and water mix?
Soap molecules interact with both water and grease.
That is central to why soap cleans.
Soap can surround tiny oily droplets and help keep them dispersed in water long enough to wash them away.
Is density the only reason they separate?
No.
Density explains why the oil layer ends up above the water once the liquids separate.
Their molecular incompatibility explains why they form separate layers in the first place.
Both ideas matter.
Do all oils float on all liquids?
No.
Whether something floats depends on the densities of the specific materials involved.
The everyday kitchen case works because most cooking oils are less dense than water.
So oil floats because it both avoids mixing well with water and usually weighs less per unit of volume than the water underneath it.
And that’s the short explanation.
Related explanations: Why does soap clean?, Why does sugar dissolve in water?, and Why do bubbles eventually pop?