plugins/parent-fit/README.md
The parent fit plugin extends the data-sizes="auto" feature to also calculate the right sizes for object-fit: contain|cover image elements as also height ( and width) constrained image elements in general.
// never try to import *.min.js files
import lazySizes from 'lazysizes';
import 'lazysizes/plugins/parent-fit/ls.parent-fit';
For this to work properly the physical aspect-ratio of the image candidates need to be calculable. To do so either a data-aspectratio attribute has to be provided on the source/img element(s) or through width and height content attributes or at least one of the image candidates inside the srcset attribute also need to include a h (height) descriptor. (MS Edge has problems to read image candidates using the h descriptor, which is fixed by the respimg polyfill)
Simply include this plugin, combine your width descriptors with height descriptors and use object-fit. (To get object-fit support into IE9-11 use the object-fit polyfill.)
<!-- Usage of the data-aspectratio attribute: Divide width by height: 400/800 = data-aspectratio="0.5" -->
<!-- Usage of the h descriptor -->
This plugin also supports calculating height and width constrained images based on a parent element.
To do so include this plugin, combine your width descriptors with height descriptors and add the attribute data-parent-fit with either "contain" or "cover" as the keyword.
<div style="width: 400px; height: 400px; display: flex; align-items: center; justify-content: center;">
</div>
In case the width keyword is used, lazySizes simply takes the width of the parent container instead of the img element itself. In this case a h descriptor isn't necessary.
Normally the next closest parent that is not a picture element is used as the parent (i.e.: :not(picture)). This can be changed using the data-parent-container option. It takes any simple selector. If you want to use the viewport as the parent simply add html.
As a special keyword the value self can be used to signalize, that image itself should be taken.
data-parent-fit and data-parent-container with CSSThese option can also be set via CSS by abusing the font-family property.
The data-parent-fit option is called here parent-fit and data-parent-container is called parent-container:
img.my-image {
font-family: parent-container: html; parent-fit: contain;
}
Note: This plugin should be also added, if you use the bgset plugin in combination with data-sizes="auto" and background-size: cover|contain and it is also the base of the object-fit polyfill plugin.