The money comes from advertisements.
Take a YouTube video for example. Once a YouTuber gets enough subscribers and views on their videos, they have the option to enable ads. Have you ever seen an ad on a video? Yes, those are the ones.
What happens is that companies makes ads and pay YouTube to show them on their websites (and videos). When a video is posted, one can enable ads to show on the videos. When a viewer clicks the ad, the creator of the YouTuber will get a certain amount of money, and YouTube itself will get a certain amount of money.
In essence, the companies make the ads, pay YouTube to show them, viewers click on the ads, and YouTube shares a small commission to the creator of the videos.
If the video turns viral, that portion can turn quite huge.