Jesus Navas scored in the 88th minutes to knock Croatia out of Euro 2012 in what was otherwise a nervous performance from the world champions.
Croatia needed a draw to have any hopes of advancing to the last eight of the tournament, but Italy won the other Group C match 2-0 against a resilient Republic of Ireland to finish second and go through.
Xavi Hernandez chipped a clever pass to Andres Iniesta who found Navas alone in the box to smash the winner into an empty net.
Spain dominated possession as usual, seeing 62% possession but they would have liked to see off the match earlier than just two minutes from regulated time.
In what was an unconvincing performance, the Spanish defence was under constant threat from Luka Modric and Mario Mandzukic. But the chance of the night fell to Ivan Rakitic, whose header was brilliantly saved by Spanish skipper Iker Casillas.
The introduction of Cesc Fabregas and Jesus Navas made a huge difference to Spain’s attacks which were constantly thwarted by a Croatian side driven with the desire to cause an upset. Fabregas should have scored his third of the tournament but he tried to take the ball to his right foot rather than pull the trigger with his left when he had the chance.
Defensive midfielder Sergio Busquets could have also given Spain some breathing space when three of the La Roja forwards broke together, but instead of taking an attempt himself, he tried to lay it up for his team-mate, only to see his pass blocked.
In the first half, Sergio Ramos made a rash challenge on the edge of the penalty box but a writhing Mandzukic could not convince the referee for a spot-kick.
The group was precariously poised with Italy leading most of the match against Ireland by a goal before a late Mario Balotelli side sealed qualification. That meant Spain had to find a goal to assure themselves a passage to the quarters and Vicente del Bosque will be looking at an early goal in the next match rather than leave it so late.
Spain and Italy will now face either England or France depending on tomorrow’s Group D results.