Slumping shortstop J.J. Hardy homered for the Brewers, who had lost five of their previous six games. It was only the second loss in seven games for the Giants.
Friday's game figured to be a low-scoring showdown between two of the National League's best pitchers. Gallardo (8-4) certainly delivered, giving up a first-inning home run to Pablo Sandoval before settling down to retire 16 Giants batters in a row between the second and seventh innings.
Gallardo struck out nine while giving up four hits and three walks, exiting to a standing ovation with two outs in the eighth.
Cain (9-2) got off to a shaky start and went on to have a disappointing outing -- by his standards, anyway. His five runs allowed tied a season high, although he also tied a season high with nine strikeouts. Cain had given up a total of two runs over 17 innings in his previous two outings.
Craig Counsell led off the Brewers' half of the first inning with a triple, taking third after the ball scooted past left fielder Randy Winn. After a Hardy strikeout, Braun -- whose at-bat introduction music was changed to Michael Jackson's "Smooth Criminal" for the game -- doubled to score Counsell.
Casey McGehee doubled to score Braun, giving the Brewers a 2-1 lead.
Hardy, whom Brewers manager Ken Macha moved up to No. 2 in the lineup in hopes of waking his dormant bat, responded with a solo home run in the third to give the Brewers a 3-1 lead. It was the seventh homer of the season for Hardy, who came into Friday's game hitting .215.
Cain then got into more trouble in the fifth. Cain walked Gallardo, a good-hitting pitcher, and Counsell before Hardy bunted for a base hit, loading the bases with nobody out.
Braun then singled past the glove of shortstop Juan Uribe to score Gallardo. Prince Fielder followed with a flyball to shallow center field, allowing Counsell to tag up and slide past a tag attempt by catcher Bengie Molina to give Milwaukee a 5-1 lead.
NOTES: Giants manager Bruce Bochy said before Friday's game that he still hadn't decided on a starter for Sunday's series finale in Milwaukee. ... Green Bay Packers first-round draft picks B.J. Raji and Clay Matthews III took batting practice and threw out ceremonial first pitches before the game. ... Recent flooding at Miller Park damaged more than 6,000 Jason Kendall bobble head dolls, meaning some fans will receive vouchers for Sunday's planned giveaway.