You asked two questions: How does it balance, and why does it do this? Charlie answered "Why does it do this?", and he did so quite well, especially since, as his sources suggest, even the biologists do not completely understand it yet.
As for how it balances...
It does indeed appear at first to defy gravity. The birds center of mass is moving relative to the platform it is standing on, and it looks like it is moving in the wrong direction, since the head and neck are extending out away from the direction of movement of the twig (indeed, they would have to in order to keep the head still relative to the environment).
However, after watching that animation play through many times I have convinced myself that the bird is indeed moving other parts of its body to compensate. It does move its legs, its belly, and other body parts at times in order to compensate for the motion and thereby balance itself.
It does not look like it, but the body motion is there. It is just very difficult to see unless you are specifically looking for it, and even once you spot it the balancing motions are very, very small.
It is like when we stand in one place, we have to keep adjusting our bodies constantly to not fall over. We do it without even thinking about it. This is even more amazing in the case of the bird since it has to not only stay upright but do so against the motion of the twig; however, the mass of the neck and head is probably very, very small proportional to the mass of the rest of the body which is doing the balancing, and that would mean that the rest of the body does not need to move much.
And that seems to be how the bird is balancing on the twig while keeping its head like that. At least, I have convinced myself as much by watching that animation replay too many times. ;)