Every eleven years (more or less precisely) sunspots are seen to rise in numbers. The magnetic field of the sun changes polarity over eleven years and this is the reason the number of spots can vary. But I'm not sure I understand why a flip occurs. On Earth, this can be seen at times too, but only at a longer time scale. Is this difference due to the sun being gaseous rather than liquid? Why is the periodicity so steady? Why does the flip occur in the first place? It surely has to do with the sun's rotation, but I don't see clearly how.
Why is the periodicity so steady?
It's not so steady. Some solar cycles have lasted for nine years, others for fourteen years. Of the 26 solar cycles between 1700 and the present, 21 had a span between 10 and 12 years.
Why does the flip occur in the first place?
Nobody knows. There are various conjectures, but they're just conjectures.
The solar cycle, which is observed in terms of sunspots, is definitely associated with the polarity of the Sun's polar magnetic field; the flip from one polarity to the other occurs near the peak of a solar cycle. The polar magnetic field drives the solar cycle, but why the polar magnetic field alternates from one polarity to another, and then back again, nobody really knows.
The Earth's magnetic field also flips and flops. The 1950s discovery that the Earth has experienced alternations in its magnetic fields over time was one of the driving discoveries that led to the theory of plate tectonics. Dynamos can change polarity. Why that happens? Nobody knows. Nobody knows if the flips and flops in the Earth's magnetic field and the flips and flops in the Sun's magnetic field have the same underlying cause.
One last thing: It's perhaps better to look at the cycle as lasting 22 years. That is how long it takes for the Sun's magnetic field to flip its polarity and then flip back again. There are differences between the even and odd 11 year solar cycles.