Former minister and fiction writer Alvarado Quesada, 38, had 61 percent of the vote with results in from 91 percent of polling stations. His rival, Alvarado Munoz, a 43-year-old former TV journalist, had 39 per cent of the vote.

Alvarado Quesada, who will be the youngest president in the modern history of Costa Rica, used the campaign to appeal to the progressive streak in a country known for pacifism and ecological stewardship.

Alvarado Munoz, best known for religious dance songs and ballads, has vowed to restore what he calls traditional values by preventing gay marriage and restricting women’s access to abortions.

The election exposed deep divisions in the Central American tourist destination known for its laid-back beach culture and pristine rainforests, but whose rural communities remain socially conservative.

It could also reflect the mood elsewhere in Latin America, where several countries that have backed same sex unions are holding elections in 2018.

At a polling place in the western Pavas neighborhood of the capital San Jose, Alvarado Quesada, until recently a minister in the outgoing government also known for his student rock band, voted and spoke briefly to supporters.

“Costa Rica is an amazing country and we want to not only preserve its great democracy, its peaceful nature, its respect for the environment and human rights, but we also want to move Costa Rica forward,” he said.

Shortly after Alvarado Munoz cast his vote at a school in the capital he pledged to lead a government free of bias, in a possible sign that he had sensed his hardline stance was turning off centrist voters.

“We’re going to work for everyone and we won’t discriminate against anyone. We will protect all groups that have felt vulnerable ... people with disabilities, people with different sexual orientations,” he told reporters.