Pure CSS is not done.
If you say that images load dynamically, then there is some kind of javascript that does this. So, after loading the image, you can check its size, match the size of the block, and change the background-size . However, if the block size can change over time, it makes sense to recalculate the background-size when resizing (as a rule, it’s enough to subscribe to the window.resize event).
However, if there are many such blocks, the above approach will cause lags. In addition, in some browsers for background-image , anti aliasing is not supported, which leads to a noticeable deterioration in picture quality when scaled.
Perhaps you should use <canvas> or <svg> instead of changing the background dynamically?
You can also come up with such a construction: the main <div> does not set the background. Instead, put another <div> or <img> with absolute positioning and max-width inside and set the background for it. Here, however, problems with vertical alignment will begin, and indeed this is not a very good solution: the html code will lose readability. However, it will work faster than subscribing to events, as there is less software manipulation with the DOM.