In a majority decision made public on Thursday, the court backed the opinion of the San Jose-based Inter-American Court of Human Rights, which said in January that countries in the region should legalize same-sex unions.
Legalizing gay marriage was a major campaign promise by President Carlos Alvarado Quesada, who took office in May.
In recent years, same-sex couples have been allowed to marry in Argentina, Brazil, Colombia, Uruguay and parts of Mexico.
“It’s now just a matter of time. Full equal rights will come, love will prevail,” Alvarado Quesada tweeted on Thursday.
The ruling is scheduled to be published in the official gazette next week and will take effect 18 months afterward.
The court’s ruling, “which confirms the unconstitutionality of the articles that prohibit equal civil marriage, is a big step forward toward equality,” the president added in his tweet.
The centre-left, Alvarado Quesada, decisively defeated a conservative opponent in Costa Rica’s presidential runoff in April, by promising to allow gay marriage and protect the country’s reputation for tolerance.
Alvarado Quesada said regulations would be modified to comply with the court ruling.
Despite Costa Rica’s reputation as a socially forward- looking nation, with high education and health standards, reproductive rights such as in vitro fertilization and abortion are not widely accepted, polling has shown.
Barely 30 percent of Costa Ricans favored same-sex marriage, according to a survey released in January by the CIEP think tank of the University of Costa Rica.
Costa Rica’s first same-sex wedding was blocked in January by notaries who refused to recognize it until laws forbidding gay marriage are changed.
Pro-government lawmaker Enrique Sanchez, an activist for LGBT+ rights, said legal reforms to implement the law should be carried out smoothly, since the debate on whether same-sex marriage is legal had been settled.
“This is already a legal reality and now we must concentrate on making the adjustments to implement the law and continue to promote a culture of integration and tolerance in society,” he said.
The Catholic Church’s Episcopal Conference of Costa Rica criticized the ruling.
“In the natural order of things, that basic family nucleus of society is based on monogamous and heterosexual marriage,” it said in a statement.