Ali scored a painstaking 117 off 308 balls but Pakistan lost six second-innings wickets after lunch, the last five going for 28 runs at the P Sara Oval.
Dhammika Prasad (4-92) was the pick of the Sri Lankan bowlers, while Dushmantha Chameera (3-53) also impressed.
Read: Cricket: Pakistan fight back in second Sri Lanka Test
Resuming on 171 for two, Ali led Pakistan's reply with a dour display of resolute batting despite losing senior batsmen Younus Khan (40) and captain Misbahul Haq (22) in the morning session.
Sri Lanka skipper Angelo Mathews made the breakthrough when he induced Younus to edge a delivery behind and Prasad then trapped Misbah leg before.
The Pakistan skipper reviewed the decision but could not get the verdict overturned.
Ali took 266 balls to bring up his ninth test century, a knock of unflattering strike rate as well as unwavering determination spread over eight-and-half hours.
Read: Day two: Sri Lanka lead Pakistan by 166 runs in second Test
He took two runs off Chameera and was celebrating his hundred even though the third umpire was still checking whether he had been run out by Mathews' direct throw from mid-off. Ali was adjudged leg before to Prasad on 114 but the batsman reviewed the decision and got it overturned. He could only add three more runs before falling to spinner Rangana Herath.
Wahab Riaz (six) came out to bat with a fractured hand and was the last Pakistani batsman to be out.
COMMENTS
Comments are moderated and generally will be posted if they are on-topic and not abusive.
For more information, please see our Comments FAQ