By absorbing ultraviolet light, and turning it into heat. Molecules that absorb particular wavelengths of light are called dyes. A sunscreen is a dye that absorbs the invisible ultraviolet light that causes sunburn.
One such dye molecule is benzophenone-3. It blocks primarily the UVB light that causes sunburn, but not much of the UVA light that can cause skin cancer.
Another sunscreen, avobenzone, is better at blocking both forms of ultraviolet light. There are at least 23 other similar compounds that act in much the same way.
A different type of protection is offered by sunblock. In a sunblock, the ultraviolet light is reflected instead of being absorbed. In some sunblocks, almost all light is reflected, including visible light, so the product looks bright white. In others, the size of the reflecting particles in the cream is carefully selected so that visible light is not reflected, and the skin colors are not blocked.
Sunblocks typically include the same pigments used in white paint, specifically titanium dioxide and zinc oxide. Zinc oxide is better at blocking the entire ultraviolet spectrum than titanium dioxide.