Sri Lanka's left-arm spinner Prabath Jayasuriya continued his dream start in Tests by picking up his third five-wicket haul in as many innings and helped the hosts, who made 222 after batting first, to reduce Pakistan to 85-7 at one stage.
But Pakistan added 133 for their last three wickets to reach 218, courtesy of Babar's heroic 119 before the 27-year-old became the final wicket to fall for the touring side.
Sri Lanka extended their overall lead to 40 at the close of play, reaching 36-1 after losing captain Dimuth Karunaratne for 16 in their second innings.
Babar curbed his attacking instincts and farmed most of the strike to shield his tail-end batters, adding 27 for the eighth wicket with Yasir Shah (18), another 36 for the ninth with Hasan Ali (17) and a further 70 for the last with Naseem Shah (5).
The stylish right-hander, who during his knock became the fasTest Pakistan batter to complete 10,000 international runs, leapt and punched the air as he scampered for a single off spinner Maheesh Theekshana to get to his century.
Number 11 batter Naseem scored his first run on the 39th ball he faced, showing resolute defence to hang around with his skipper during his unbeaten 52-ball stay.
Sri Lanka have won 22 of their 39 previous Tests matches at the Galle International Stadium, where the pitch offers a lot of turn and bounce for the spinners, and the hosts' slow bowlers once again put them in a dominant position.
The 30-year-old Jayasuriya, who took 12 wickets on debut against Australia at the same ground recently, spun a web around Pakistan's middle-order batters with figures of 5-82. The off-spin duo of Theekshana, who dismissed Babar, and Ramesh Mendis provided able support by picking up two wickets each.
Mohammad Rizwan's 19 was the second-highest score behind Babar in Pakistan's first innings.