This is something known as the Cheerios Effect. Because of the buoyancy of the water, a light object, for example a cork or bottle cap is forced to occupy the highest position on the surface of the water. Now as shown in the image:

The highest point of the water is at it's edges because of the strong force of adhesion between the glass and the water. So naturally the bottle cap moves to the edge to occupy the highest position available.
Interestingly when filled upto the brim, the same force of adhesion pulls the water at the edges down but the water at the centre has no pull on it (due to force of adhesion, cohesive force is omnipresent) and now the highest point is at the centre so that's where the cap resides.
This also means that in theory (never tried it) if you filled half the cup with mercury the bottle cap should stay at the centre because of its convex meniscus.