Samuel Chukwueze was in a superlative form as he scored twice to secured victory for Villarreal at the Santiago Bernabeu.
The Nigerian hit a curled finish late on to leave Real 12 points behind leaders Barcelona, having played a game more.
The hosts had taken the lead through a Pau Torres own goal but Chukwueze slotted in an equaliser.
Vinicius Jr’s solo strike put Real ahead but Jose Luis Morales equalised before Chukwueze stunned the hosts.
With just 10 La Liga games remaining, Real would need a strong finish to the season and an unlikely Barcelona collapse to defend their title.
Real thought they had an opportunity for a late equaliser when they were awarded a penalty after the referee felt Aissa Mandi handled the ball as he fell to the ground inside his own box.
However, Javier Alberola Rojas overturned that decision after going to the pitchside monitor following a VAR review.
The win moves Villarreal up to fifth in the table, four points off the top four.
Barcelona, meanwhile, could move 15 points clear at the top when they host Girona on Monday.
Samuel Chukwueze was named the Man of the match after his stunning performance on the night.