"It was approved overall by 39 votes in favor and 20 against, with five abstentions," said a spokesman for the bill's chief sponsor, assemblyman Davi Razu.
Spokesman Oscar Oliver said the city's majority leftist legislators also defeated an opposition amendment to the gay marriage bill that would have prevented same-sex couples from adopting children.
"For centuries, unjust laws prohibited marriage between whites and blacks or Europeans and (indigenous) Indians," Democratic Revolutionary Party (PRD) lawmaker Victor Romo said.
"Today all those barriers have come down."
The new measure modified a civil union law already on the books in Mexico City, as in other Latin American nations including Uruguay and Colombia.
In Argentina the Supreme Court is to rule on a court-approved gay marriage that was challenged earlier this month.
The Mexico City law changes the meaning of marriage from "a free union between a man and a woman" to "a free union between two people."
Mexico City's gay marriage bill was fully backed by lawmakers from the PRD, which has ruled Mexico's sprawling capital since 1997. It was opposed by the country's ruling National Action Party (PAN).
The vote was preceded by a lively, three-hour debate during which President Felipe Calderon's conservative PAN issued a statement calling the gay marriage bill "an electoral ploy by the PRD that mocks and abuses the gay community."
Outside the city's assembly building, about 100 gay rights activists demonstrated in favor of the marriage bill, some holding up signs saying: "Be Happy, Be Gay." Read complete article & view photos - AFP