Elgar’s 103, his second test century, put South Africa in a strong position at tea on 194 for one, but following his dismissal in the third over of the final session, the visitors slid to 268 for five wickets at close.
Quinton de Kock, unbeaten on 17, and nightwatchman Dale Steyn were at the crease when stumps were drawn.
Fast bowler Suranga Lakmal struck two decisive blows for Sri Lanka to bring his team back into the reckoning.
He first got rid of Elgar, who hit 11 fours and three sixes, when the batsman flashed at a wide delivery and edged a catch to wicketkeeper Dinesh Chandimal.
In the penultimate over of the day, Lakmal, with the second new ball which was taken after 85 overs, bowled out AB de Villiers for 21.
Spinners Rangana Herath and Dilruwan Perera toiled all day and picked up a wicket each in the final session.
Herath’s tight length frustrated Hashim Amla, who was making his debut as test captain, and he ended up hitting a catch to Perera at extra cover after scoring just 11.
Perera accounted for Faf du Plessis (80) when he fell to a bat-pad catch to Kaushal Silva.
Du Plessis hit five fours and a six during his knock and shared a second-wicket stand of 125 with Elgar.
Neither Elgar nor Du Plessis allowed the Sri Lankan spinners any chance to settle into a rhythm, using their feet well to block anything pitched on a good length or getting to the pitch of the ball to hit through the line for boundaries.
With the pitch hardly offering any assistance, Sri Lanka adopted different fielding strategies for the batsmen.
Although they did not succeed in breaking the partnership, they managed to restrict the scoring rate with the second session producing just 83 runs off 32 overs.
South Africa had reached lunch on 111-1 after Amla won the toss and elected to bat.
The wicket of Elgar’s opening partner Alviro Petersen was the only success Sri Lanka had in the first two sessions.
After an opening stand of 70, off-spinner Perera gave Sri Lanka the breakthrough by trapping Petersen leg before on the back foot for 34, a decision confirmed after an unsuccessful review by the batsman.
Sri Lanka lost the services of fast bowler Shaminda Eranga in the final session when he attempted to stop a powerful drive from Du Plessis off Herath at mid-off and split the webbing between his right thumb and index finger.
Eranga left the field for treatment and did not take any further part in the match.
“Eranga had eight stitches inserted in the webbing of his right hand and was unable to take the field,” Sri Lanka manager Michael de Zoysa told reporters.
“We will monitor his progress and see whether he will be able to bowl tomorrow (Thursday).” (Reuters)