ISTANBUL — As he stood on the top of his campaign bus before a sea of supporters on election night, Ekrem Imamoglu, Istanbul’s mayor-elect — the man who beat President Recep Tayyip Erdogan and his all-powerful party machine twice — hugged a teenager who had by chance helped him win over the city.

Running alongside the then-candidate’s bus in March, the boy, Berkay Gezgin, had shouted to him: “Don’t worry, brother Ekrem, everything will be fine.”

It became the campaign’s slogan, because it captured exactly the spirit that Mr. Imamoglu, a virtually unknown district mayor, was trying to evoke as he took on one of the heavyweights of the ruling party — not to speak of Mr. Erdogan himself.

Mr. Imamoglu, 49, beat Mr. Erdogan’s candidate first in March and again in a rerun on Sunday. His winning formula was a message of optimism and love that sought to appeal to the religious conservatives who formed the base of Mr. Erdogan’s support, as well as nationalists and the important Kurdish minority.