Density Anomaly in Cooling
It turns out that this tricky property is called a density anomaly. The same pattern is typical not only for water, but also for some other substances, such as germanium, silicon, gallium, antimony, bismuth, and cerium.
If we go back to water, however, things are quite interesting. First, water really gets denser as it cools and reaches its maximum density at +4 degrees Celsius. All the while, the volume of water being cooled does decrease. But then the volume of the cooled water begins to increase even though it is cooling, it crystallizes and the ice also increases in volume, which exceeds the volume of the original liquid.
This tricky feature makes water ideal for filling a body of water. After all, if rivers and lakes had any other liquid, the crystallization of that liquid would cause pieces of that "ice" to sink.Well, ice from ordinary water, lighter than water itself, so it floats perfectly on the surface. So a body of water can be covered with a crust of ice, and under it there will be water that will not freeze and allow the underwater inhabitants to survive the cold weather.
What happens on an "atomic" level
The answer to "why" already exists. Let's remember what a water molecule looks like. It's painted on almost every fence.
One big ball representing an oxygen atom and two smaller balls representing hydrogen atoms. In order to join together into a group of molecules, the atoms need to make chemical bonds. Trying to make these bonds orients this strange shape of a water molecule in space and makes it magnetic to other atoms.
As long as the molecules are mobile and crystallization has not begun, they simply hold each other close. Water is then liquid. When the mobility of the water molecule decreases due to cooling, the molecules begin to move much less and, due to their asymmetric structure, form complex structures.
These structures resemble rhombuses, with HOH molecules at the tops. Such a structure inevitably occupies a larger volume than simple water. It turns out that the volume of crystallized water increases because of the construction of a crystal structure in which the distance between the molecules is greater than that of liquid water. And the distance itself is determined here by the specifics of the interatomic bonding, which orients the molecules relative to each other.