Issues with ampshared.css styles on pre-valid AMP pages using img elements

Demonstration of two issues with ampshared.css incorrectly applying to img elements on β€œprevalid” AMP pages. This page is currently invalid AMP but it may become so once native img elements are allowed.

SSR'ed amp-img > img which has width & height

An amp-img > img element gets a fill layout with absolute positioning inside of its statically-sized container. As such, the img does not need a width or height. When AMP Optimizer does SSR, the img may be prerendered as a hero, in which case the page will have the img in the original markup without waiting for the AMP runtime to create it lazily. A problem arises when optimization layers like Mod_Pagespeed may see such img elements and automatically add width and height attributes in a well-intentioned attempt to reduce CLS (see incubator-pagespeed-mod#2067). This causes two problems in AMP:

  1. The validator doesn't allow width and height attributes on SSR'ed hero img elements, resulting in an invalid AMP page.
  2. The ampshared.css stylesheet has two rules with selectors containing [width][height][sizes] which inadvertently gives the element position:relative, which has the effect of hiding the image when intrinsic layout is applied since the sizer pushes it into the overflow.
Expected Actual
See screenshot of above comparison in case the issue is fixed

Native non-AMP img elements with width, height, and sizes attributes

Similarly to the above, when a non-AMP img is used on the page and it has width, height, and sizes attributes then the aforementioned CSS rules will give the element positoin:relative when it may be needing absolute positioning. This issue will become more and more common once amp-img is deprecated, as img[loading=lazy][decoding=async][width][height][sizes] elements will start appearing on AMP pages much more often.

For example, consider the Cover Block in WordPress which has an image positioned absolutely with a fill layout and some text overlaying it. In the following example, the fill layout is broken because relative positioning is being applied.

Expected Actual

lo-fi beats

lo-fi beats

See screenshot of above comparison in case the issue is fixed

Note that since the element has responsive layout it's not expected to look exactly the same as the above.

Conclusion

The two problematic CSS selectors in ampshared.css are:

  1. [width][height][sizes]:not([layout]):not(.i-amphtml-element)
  2. [width][height][sizes]:not([layout]):not(.i-amphtml-layout-responsive)

The latter was introduced in #28115 while the former is much older, originating in #12077.


@westonruter