The capital's mayor is expected to sign the bill into law
Lawmakers in Mexico City have become the first in Latin America to legalise gay marriage.
City legislators passed the bill 39-20, with five abstentions. The city's mayor is now widely expected to sign the bill into law.
Gay marriage is only allowed in seven countries and some parts of the US. Certain parts of Latin America allow civil unions for same-sex couples.
The Catholic Church and conservative groups had opposed Mexico City's move.
The bill calls for a change in the definition of marriage in the city's civic code - from the union of a man and a woman to "the free uniting of two people".
Lawmaker David Razu had proposed the change to give same-sex couples the same rights as heterosexual couples regarding social security and other benefits.
Mexico City's legislature is dominated by the leftist Democratic Revolutionary Party, which has already legalised abortion and civil unions for same-sex couples.
Spokesman Oscar Oliver told AFP news agency that city legislators were now taking up a measure in the bill that would allow married same-sex couples to adopt children.
A handful of cities in Argentina, Ecuador and Colombia permit gay unions.
Uruguay alone has legalised civil unions nationwide and allowed same-sex couples to adopt children.
Last month, an Argentinean court narrowly blocked what would been the continent's first gay marriage.
In a last-minute challenge, a court referred the case to the country's Supreme Court, which is due to rule on the issue.