The bill passed the capital's local assembly 39-20 to the cheers of supporters who yelled: "Yes, we could! Yes, we could!"
Leftist Mayor Marcelo Ebrard of the Democratic Revolution Party was widely expected to sign the measure into law.
Mexico City's left-led assembly has made several decisions unpopular elsewhere in this deeply Roman Catholic country, including legalizing abortion in the first 12 weeks of pregnancy. That decision sparked a backlash, with the majority of Mexico's other 32 states enacting legislation declaring life begins at conception.
The conservative Nation Action Party of President Felipe Calderon has vowed to challenge the gay marriage law in the courts. However, homosexuality is increasingly accepted in Mexico, with gay couples openly holding hands in parts of the capital and the annual gay pride parade drawing tens of thousands.
The bill calls for changing the definition of marriage in the city's civil code. Marriage is currently defined as the union of a man and a woman. The new definition will be "the free uniting of two people."
The change would allow same-sex couples to adopt children, apply for bank loans together, inherit wealth and be included in the insurance policies of their spouse, rights they were denied under civil unions allowed in the city.
"We are so happy," said Temistocles Villanueva, a 23-year-old film student who celebrated by passionately kissing his boyfriend outside the city's assembly.
Only seven countries allow gay marriages: Canada, Spain, South Africa, Sweden, Norway, the Netherlands and Belgium. U.S. states that permit same-sex marriage are Iowa, Massachusetts, Vermont, Connecticut and New Hampshire.
Argentina's capital became the first Latin American city to legalize same-sex civil unions in 2002 for gay and lesbian couples. Four other Argentine cities later did the same, and as did Mexico City in 2007 and some Mexican and Brazilian states. Uruguay alone has legalized civil unions nationwide.
Buenos Aires lawmakers introduced a bill for legalizing gay marriage in the national Congress in October but it has stalled without a vote, and officials in the South American city have blocked same-sex wedding because of conflicting judicial rulings.
Many people in Mexico and elsewhere in Latin America remain opposed to gay marriage, and the dominant Roman Catholic Church has announced its opposition.
"They have given Mexicans the most bitter Christmas," said Armando Martinez, the president of the College of Catholic Attorneys. "They are permitting adoption (by gay couples) and in one stroke of the pen have erased the term 'mother' and 'father."'
City lawmaker Victor Romo, a member of the mayor's leftist party, called it a historic day.
"For centuries unjust laws banned marriage between blacks and whites or Indians and Europeans," he said. "Today all barriers have disappeared."