Chasing 287 to win, India overhauled the target with two balls to spare and took a 2-1 lead in the five-match series.
Gambhir's 11th ODI century could have gone down the drain had Raina not played that heroic innings in company of Irfan Pathan (34 off 31) down the order.
The two-left handers added 92 runs in their unconquered sixth-wicket partnership and piloted India to highest ever successful run chase on the Sri Lankan soil.
Raina's 23rd half-century, adorned with six fours and one six, while Pathan's innings had three boundaries.
After electing to bat, Sri Lanka put on an impressive 286 for five with Kumar Sangakkara (73), Angelo Matthews (71 not out) and skipper Mahela Jayawardene (65) scoring half-centuries
For India, pacer Zaheer Khan (2/39) accounted for two wickets while Irfan Pathan, Ashok Dinda and Rahul Sharma chipped in with a wicket apiece.
More From This Section
India's chase, though, was shaky with Virender Sehwag (3) becoming the first victim when Thisara Perera had him caught in covers.
Gambhir and Kohli then put on 105 runs for the second wicket to repair the innings. Spinner Rangana Herath separated them when he caught Kohli off his own bowling in the 21st over.
India skipper Mahendra Singh Dhoni promoted himself up the order and made a useful 31, adding 67 runs with Gambhir for the third wicket.