Opening batsman Markram made 85 not out as South Africa reached 167 for five at tea, a distant 250 runs short of an improbable target of 417.
Markram and Theunis de Bruyn, South Africa's two least experienced batsmen, held up the Australians for almost two hours in a fifth wicket stand of 87 after coming together at 49 for four.
De Bruyn, playing in his fourth Test, made a stylish 36 before he was caught behind off Josh Hazlewood. It was the only wicket to fall during the afternoon.
Markram and Elgar put on 29 for the first wicket before Elgar edged a sharply lifting delivery from Mitchell Starc to wicketkeeper Tim Paine to be out for nine.
Also Read
Amla avoided a pair but only made eight before he was leg before wicket to Hazlewood.
South Africa then suffered a hammer blow when De Villiers, their top scorer in the first innings, was run out for nought.
Markram turned a ball from off-spinner Nathan Lyon behind square leg and did not respond when De Villiers called him through for a run. De Villiers had to turn and tried to go back but could not beat David Warner's throw to Lyon.
Markram, in his seventh Test, showed good composure, a sound technique and some cracking off side drives in a 147-ball innings which included 11 boundaries.
Earlier, Australia added 14 runs to their overnight total of 213 for nine before being bowled out for 227.
Disclaimer: No Business Standard Journalist was involved in creation of this content