In this exercise we will build a demo using Scott Jehl’s Picturefill approach.
- Download a clean build of HTML5 Boilerplate and name the project root picturefill.
- Download project imagery and place in the img directory.
- Include picturefill script (direct or via CDN). Note the use of the async attribute on the element. This tells the browser that it can load picturefill asynchronously, without waiting for it to finish before loading the rest of the document.
- Build html structure. I used a
section
element in the example. - Add base style to the main.css file. Remember mobile first!
section { height: 380px; width: 380px; margin-top: 40px; margin-right: auto; margin-bottom: 40px; margin-left: auto; border: 2px solid #666; padding: 10px; }
- Add Media Queries
@media only screen and (min-width: 600px) { section { height: 600px; width: 600px; padding: 10px; } } @media only screen and (min-width: 768px) { section { height: 768px; width: 768px; padding: 10px; } } @media only screen and (min-width: 1024px) { section { height: 1024px; width: 1024px; padding: 10px; } }
- Depending on need add the appropriate picture element in the source.
<picture> <source srcset="img/mars-xl.jpg" media="(min-width: 1024px)"> <source srcset="img/mars-l.jpg" media="(min-width: 768px)"> <source srcset="img/mars-m.jpg" media="(min-width: 600px)"> <img srcset="img/mars-s.jpg" alt="…"> </picture>
- Review documentation for additional options and usage tips.
- I want to serve high-res assets only to users with high pixel density viewports
- I want the browser to choose the best image source for a user’s pixel density and the size of the image in the layout.
- I need my image sources to change only at specific breakpoints that I define.
- I need specific image breakpoints, with multiple resolution options for each.
- I want to serve newer image formats only to browsers that support them.