For a 6-week "Professional Learning Community" initiative at work, I'm in a group focused on learning more about Eleventy, especially using Eleventy for images, and best practices for images on the web in general.
This week my task for the group was to investigate the various properties that could be set on
img and what, precisely, the most useful ones mean. Here are my notes, which are largely sourced from the MDN docs on the
height- when set, the browser will leave space for the image before it loads so the content doesn't do a visual jump
alt- used by visually impaired users and users browsing in a non-graphical browser, but also used for things like when the image is copied & pasted as text. Alt may also be shown if the image fails to load for some reason. alt='' is valid and indicates that the element is purely decorative or not key to the content of the page (like a tracking pixel). If alt='' and the image fails to load, browsers won't show the broken image indicator.
lazy. Eager is the default, and indicates the image should load immediately.
lazymeans the browser will attempt to defer loading until the image is a calculated distance from the viewport, saving bandwidth.
sizes: must be used in combination with
- one or more strings separated by commas. Each string consists of a media condition that describes properties of the viewport, and a size of image that should be used when that condition is met.
(max-height: 500px) 1000pxproposes to use a source of 1000px width, if the viewport is not higher than 500px.
- each width of image listed in
sizesshould be present in
- the last element in the list should have no media condition
srcset: one or more strings separated by commas, with possible image sources for the user agent to choose from. each string has a url to an image, and optionally, whitespace followed by a width descriptor (positive integer followed by
w) or pixel density descriptor (positive floating point number followed by
x). If no descriptor is specified, the source gets a default descriptor of
- use either all width descriptors or all pixel density descriptors in the same srcset, don't mix them. And don't have duplicates for a given descriptor either
object-positionpositions the image within the elements display box
object-fit attribute docs on MDN
object-fitadjusts the size of the image within the box.
contain: content is scaled to maintain its aspect ratio while fitting into the content box as entirely as possible. Content is 'letterboxed' if it doesn't fit exactly
cover: like contain, but instead of letterboxing, the object will be clipped to fit if the aspect ratio of the content doesn't match the object ratio of the box
fill- entire object will completely fill the box. object will be stretched to fit if the aspect ratio doesn't match
none: content is not resized
scale-down: content is sized as if
contain, whichever would result in a smaller object