The bill, which will also pave the way for gay couples to adopt children, garnered 183 votes in favor, 136 against and six abstentions in the 350-seat chamber.
It will now go to the Senate — where the Socialists have ample support — for final approval in the coming weeks. Belgium and the Netherlands are the only two other European countries that have legalized gay marriages.
Representatives of gay and lesbian groups cheered and applauded from the chamber's public gallery when the vote result was read out.
"This is a great and historic day because never before has such a small legal reform made such an important improvement in rights and in favor of freedom and equality", said Pedro Zerolo, a leader of Spain's homosexual rights group.
Groups for and against the measure gathered outside the parliament building awaiting the outcome.
In the vote, deputies agreed that the phrase "Matrimony shall have the same requisites and effects regardless of whether the persons involved are of the same or different sex" should be incorporated into Spain's Civil Law.
The measure has been fiercely opposed by Spain's Roman Catholic church and the conservative opposition Popular Party, whose deputies formed the bulk of the opposing vote Thursday.
The Spanish Bishops Conference issued a statement calling the bill approval "an error," saying it "went against the common good." It added that it was "unfair that real marriage should be treated the same as the union of persons of the same sex."
Last year, the conference's spokesman Antonio Martinez Camino said allowing gay marriage was like "imposing a virus on society, something false that will have negative consequences for social life."