Scotland has voted in favour of the UK staying in the EU by 62% to 38% - with all 32 council areas backing Remain.
But the UK as a whole has voted to Leave - raising the prospect of Scotland being taken out of the EU against its will.
First Minister Nicola Sturgeon said Scotland had delivered a "strong, unequivocal vote" to remain in the EU.
David Cameron has announced he will step down as prime minister by October.
Speaking in Downing Street, he said he would "steady the ship" until then - but would hand over to a new leader in time for the Conservative Party conference.
Scottish Conservative leader Ruth Davidson tweeted: "Right for the Prime Minister to offer stability while the country plots its course. Honorable to the last."
Follow the latest reaction from Scotland on our live page
Five facts from the EU referendum vote in Scotland
US presidential hopeful Donald Trump, who has arrived in Scotland to visit his Trump Turnberry golf resort, said it was a "great thing" that the people of the UK had "taken back their country".
With all the votes declared, the Leave side won by a margin of 52 % to 48%.
Nicola Sturgeon issued a statement during the night as it became clear the Leave side was heading for victory.
She said the vote had made clear "that the people of Scotland see their future as part of the European Union".
She added: "We await the final UK-wide result, but Scotland has spoken - and spoken decisively."
She will give a fuller response from the Scottish government from her official residence in Edinburgh later.