Elgar scored a career-high 129 and shared a 103-run partnership with De Kock to lift the home side into a handy position after they had struggled early on.
The opener went past his previous top Test score and his ton came up off 186 balls before he was caught by wicketkeeper Kusal Mendis off Suranga Lakmal half an hour before the close.
De Kock, whose runs came off 90 balls, will resume with nightwatchman Kyle Abbott unbeaten on 16.
Teenager Lahiru Kumara claimed three wickets, including two in the same over, after he was brought into the side following Sri Lanka's 206-run defeat in the first Test in Port Elizabeth.
But the touring side will feel they did not take full advantage of the seamer-friendly track as they took as many wickets in the second two sessions as they had before lunch when South Africa were teetering on 69-3 after losing the toss and being put into bat.
There was an immediate breakthrough before the home team had scored a run with Stephen Cook, who made a century and was named man of the match in the first Test, out to the fourth ball of the game. He pushed at a rising delivery from Lakmal and got a faint edge to Mendis.
The 19-year-old Kumara dismissed Hashim Amla and JP Duminy in the same over just before lunch.
Amla, continuing his indifferent form, was clean bowled for 29 and five balls later Duminy gloved a quick leg-side delivery to be caught for a duck after an acrobatic leap by Mendis.
In the second session, captain Faf du Plessis was the only wicket to fall, making 38 in a 76-run partnership with Elgar that launched South Africa's fightback. He was caught at first slip by Angelo Mathews off the left-arm spin of Rangana Herath.
After tea, Temba Bavuma, who twice went out cheaply in the first Test, was caught for 10 trying to flick a delivery over the field but taken at square leg by Upul Tharanga off Kumara.
Elgar followed with a thick edge off the second new ball but not before seeing his team into a relatively strong position.
2nd testCape Town TestDean Elgarkusal mendisLahiru KumaranewlandsNewlands TestSouth Africa vs Sri LankaSouth Africa vs Sri Lanka 2016South Africa vs Sri Lanka 2016-17Suranga Lakmal
First Published: January 2, 2017, 10:24 PM IST