The legislation goes further than a 2006 city law allowing civil unions by giving gay couples access to the same family social security benefits and joint loans as straight couples.
In a last-minute measure, the city's left-dominated assembly overcame conservative opposition to allow gay couples that marry to adopt children.
Activists in the chamber burst into cheers. Some gay men and women hugged, exchanged kisses and waved rainbow-colored flags that have come to symbolize gay rights.
We are putting an end to segregation and stigmatization of a sector of society, giving access to full marriage rights, David Razu, a legislator from the left-wing Social Democratic Party, or PSD, who promoted the law told Reuters.
The bill now goes to be signed by Mexico City Mayor Marcelo Ebrard, who has backed other progressive measures like the legalization of abortion in some cases, putting the sprawling capital at the vanguard of liberal policies in Latin America.
Homosexuality, stifled in much of the country, has come out of the closet in Mexico City where a gay and lesbian district is packed with gay bars and same-sex couples holding hands, although some say discrimination is still rampant.
Conservative lawmakers voted against the bill and vocal church leaders are likely to pressure Ebrard to veto it. Mexico's Catholic archdiocese has said that legalizing gay marriage is immoral and will destroy families.
Recognizing homosexual civil unions as marriage goes against the public good and the emotional development of our children, said Giovanni Gutierrez, a city lawmaker from President Felipe Calderon's National Action Party, or PAN.
Mexico City is joining a handful of cities in the United States and Europe by allowing gays and lesbians to marry and is taking the lead in Latin America, where some places have passed laws to legalize same-sex civil unions but have fallen short of permitting full marriage between gays.
Argentina became the first Latin American country to allow civil unions across the country by same-sex couples in 2002.
But a push for full gay marriage hit a snag earlier this year when a court blocked a local judge in Buenos Aires who issued a marriage license to two men, defying a national ban. The couple has pledged to fight the court's ruling.
Neighboring Uruguay also allows gay civil unions and became the first country in Latin America to permit adoption by gay couples in September.
(Writing by Mica Rosenberg, editing by Anthony Boadle)