Reputation: 9682
I am trying to achieve HTML-"art direction" (displaying different images for different viewport widths) in React. This is the JSX:
import LogoImg from "../../abstracts/media/logo-large.svg";
import LogoImgMedium from "../../abstracts/media/logo-medium.svg";
<picture>
<source srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`} media="(max-width: 37.5em)" />
<img
className="logo__apple"
srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`}
alt="Full Logo"
src={LogoImgMedium} />
</picture>
The breakpoint defined in the media
attribute does not seem to work. Do you guys know why? I have tried to specify it with px, rem and em.
Thanks.
Upvotes: 2
Views: 4189
Reputation: 958
You just specified the same value in srcSet
attributes of source
and img
elements, which will display the same image for all widths. This might vary, but the browser is more likely to select the medium image in that case.
To display medium image for small screens and large image, just change:
<picture>
<source srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`} media="(max-width: 37.5em)" />
<img
className="logo__apple"
srcSet={`${LogoImgMedium} 1x, ${LogoImg} 2x`}
alt="Full Logo"
src={LogoImgMedium} />
</picture>
to:
<picture>
<source srcSet={`${LogoImgMedium} 1x`} media="(max-width: 500px)" />
<img
className="logo__apple"
srcSet={`${LogoImg} 2x`}
alt="Full Logo" />
</picture>;
Upvotes: 5