The 350-seat Congress of Deputies approved the measure Thursday by a vote of 187-147 with four abstentions. The bill, a divisive plank in the ruling Socialists' platform for social reform, gives homosexual couples the same rights as heterosexual ones.
"Matrimony shall have the same requirements and effects regardless of whether the persons involved are of the same or different sex," the bill states.
Conservative opposition lawmakers said they might challenge the law in court, while the church issued a veiled call for civil authorities who oppose gay marriage to refuse to wed same-sex couples.
The bill became law immediately. The Senate, where conservatives hold the largest number of seats, rejected it last week, but that chamber is only an advisory one and final say on legislation rests with the Congress of Deputies.
Gay couples can get married as soon as the law is published in the official government registry, which could happen as early as Friday or within two weeks at the latest, parliament's press office said.
The Netherlands and Belgium are the only other two countries that recognize gay marriage nationwide. The former allows gays to adopt children, but Belgium so far is just considering it. Canada's House of Commons passed legislation that would legalize gay marriage by the end of July as long as the Senate also passes the bill, which it is expected to do.
In the United States, Massachusetts is the only state to recognize gay marriage.
In debate before the vote, Prime Minister Jose Luis Rodriguez Zapatero said the dry language of the Spanish reform masks "an immense change in the lives of thousands of citizens. We are not legislating, ladies and gentlemen, for remote, unknown people. We are expanding opportunities for the happiness of our neighbors, our work colleagues, our friends, our relatives."
The Spanish Bishops Conference lashed out at the law, saying that with it and a bill passed Wednesday making it easier for Spaniards to divorce, "marriage, understood as the union of a man and a woman, is no longer provided for in our laws."
"It is necessary to oppose these unfair laws through all legitimate means," a conference statement said, alluding to its hint last month that town hall officials who oppose gay marriage should refuse to preside over such ceremonies.