Amla and De Villiers both clobbered centuries in the highest ever third-wicket partnership in ODIs of 238. Amla scored 122, including nine fours and a six in his 113-ball knock, and De Villiers 128, his 108-ball innings featuring 12 fours and three maximums, to lead the hosts to 343 for five.
The total looked well out of Pakistan's reach until Afridi, in at seven, more than lived up to his nickname of 'Boom Boom' with a stunning 88 but his dismissal by Lonwabo Tsotsobe - when going for another big hit - left the tourists with too much work to do and they were bowled out for 309 as South Africa took a 2-1 lead in the four-match series.
Pakistan won the toss and elected to bowl. Mohammad Irfan dismissed Graeme Smith for three in the third over, the opener bowled off an inside edge and, when Colin Ingram (17) became his second victim, Kamran Akmal behind the stumps taking a catch off a leading edge, the Proteas were 42 for two in the 14th over.
But De Villiers joined Amla at the crease and the duo swiftly took the match away from their opponents.
Amla survived being dropped by Mohammad Hafeez when on 36 and that proved costly as it was not until the 300 mark was in sight that he was dislodged.
By then he and De Villiers had racked up their record stand, which eclipsed Rahul Dravid and Sachin Tendulkar's unbeaten 237 for India against Kenya in the 1999 World Cup.
Tsotsobe struck first as Pakistan begun their reply, removing Nasir Jamshed for 10. Ryan McLaren did for Akmal for 30, but Mohammad Hafeez took the score into three figures as he progressed past his half-century.
His stay was ended on 57 by Robin Peterson as the Proteas began to assert their authority. Peterson did for Younis Khan (19) and Tsotsobe for Shoaib Malik (four), bringing Afridi to the crease with his side 132 for five.
His belligerent innings brought his side roaring back into the game, the big hitter surviving being bowled off a no-ball and the loss of his partner Misbah (28) to give South Africa real cause for concern, but the knock ended after 66 minutes when McLaren held a catch at long off off Tsotsobe. And Pakistan were from then on fighting a losing cause.