It's basically because viruses and harmful bacteria are smaller than our dead skin layer. So the light gets into them and destroys their DNA/RNA.
also viruses (eg. HIV, Coronavirii,...) are often killed by oxygen in air, dry out or die in other ways when not floating in bodily fluids.