In an incredible climax to Group B, Spain set up a last-16 tie against Russia after a 2-2 draw with Morocco was enough to secure top spot.
Portugal let its position as group leaders slip in the closing minutes of their match when an injury-time penalty earned Iran a 1-1 draw against the European champions.
That was after Cristiano Ronaldo missed a penalty to put Portugal 2-0 ahead after the Euro 2016 winners had gone ahead through Ricardo Quaresma's wonderful curled finish in the first half.
Portugal will now face Uruguay in its last-16 tie.
World Cup of shocks
This is a World Cup that has already delivered a number of shocks and both Monday's Group B matches saw heavyweight sides surprised by opposition teams that simply refused to accept their place in football's established pecking order.
Spain faced Morocco at the Kaliningrad Stadium, with Fernando Hierro's men knowing only a complex set of permutations would prevent them breezing into the last 16.
Morocco had failed to score in its opening two fixtures at Russia 2018, despite two creditable performances, and had little to play for. Spain, meanwhile, hadn't tasted defeat for 22 matches in a run stretching back to Euro 2016.
Perhaps it was a degree of complacency then that led to Morocco taking the lead after just 15 minutes.
Andres Iniesta and Sergio Ramos have almost 300 caps between them but looked like total strangers as they left the ball to one another on the halfway line.
Khalid Boutaib made sure to capitalize, bursting through on goal and coolly sliding the ball through David De Gea's legs.
It was the Atlas Lions' first World Cup goal for two decades, though their lead was to last little more than two minutes.
Spain, as if stirred into action, suddenly began to play as only they can, culminating in an equalizer born on the fields of La Masia -- Barcelona's youth academy -- and finished by Isco, the star of the team's next generation.
Vissel Kobe midfielder Andres Iniesta once again made a mockery of his claim he had nothing left to give at Barcelona, surging to the byline and stroking it into Isco's path, who duly did the rest.
The Spanish still looked vulnerable, though, and only the feet of De Gea prevented Boutaib notching a second.
It was the Manchester United goalkeeper's first save of the tournament, having previously conceded all four of the shots on target he'd faced.
The first half was otherwise notable for a number of crunching challenges -- Morocco receiving four yellow cards and Spain defender Gerard Pique was perhaps fortunate not to be set off for a two-footed lunge.
The only team to receive more cautions in a single half of World Cup football since 1966 was, incidentally, the Moroccan team of 1994 which received five against the Netherlands.
The Atlas Lions certainly weren't going down without a fight, and Nordin Amrabat was inches away from scoring one of the goals of the tournament early in the second period, crashing a long-range strike against De Gea's crossbar.
Morocco fans must have wondered how their team had failed to win a single point against Iran and Portugal, such was the verve with which Herve Renard's men pressed, breaking quickly on the counter on the rare occasion Spain surrendered possession
It looked like they had secured a famous win when substitute Youssef En-Neysri towered above Ramos to send a thumping header past De Gea.
But just as the Moroccan parties started, Spain substitute Iago Aspas sent La Roja to the top of Group B.
The forward's deft backheel was initially ruled out for offside, only for Uzbekistani referee Ravshan Irmatov to award the goal following a VAR review.
A point for Spain coupled with a late equalizer for Iran against Portugal meant La Roja topped Group B by virtue of goals scored. The Moroccan players could go home with their heads held high.
Late Iran miss saves Portugal
Heading into the final group game, Iran had a chance of progressing to the knockout stages for the first time in its history but fell agonizingly short of achieving that historic feat.
Youssef En-Nesyri's controversial injury-time penalty gave the underdogs hope and a sensational victory could have been achieved had Mehdi Taremi hit the target instead of the side-netting when clear on goal in the 94th minute.
In an incident-packed match, VAR came into play on numerous occasions, and controversially so, as it was questionable whether either penalty should have been awarded.
Having initially dismissed Portugal's penalty appeals, referee Enrique Cacereas belatedly deemed that Ronaldo had been brought down by Morteza Pouraliganji's challenge after a VAR review.
Many would have assumed that Portugal would have doubled its advantage following Quaresma's beautiful strike on his first World Cup start when Ronaldo -- scorer of many record-breaking goals in this tournament -- stepped up to take the 53rd-minute penalty.
But Ali Beiranvand, who had endured a number of uncertain moments under the high ball in the first half, dived to his left to keep out the Real Madrid forward's poor effort.
Following another lengthy VAR review, Cacereas awarded a yellow to Ronaldo after the Portugal captain tussled with Morteza Pouraliganji down the right flank, a decision which angered the forward.
And with Portugal set for a victory which would have secured top spot in Group B and, on paper at least, an easier last-16 tie against Russia, Cacereas again used VAR and decided that substitute Cedric had handled Sardar Azmoun's knockdown.
It seemed a harsh decision and would have had further repercussions had Taremi scored the winner which would have secured Iran's progress at Portugal's expense.