Hi all, based on my comments in the other issue I have begun brainstorming and writing a polyfill for what an aspect-ratio
property might look like. I currently have the logic figured out, and a regex that can extract this custom property from formatted CSS, I think I'm close to a working polyfill I just need to figure out how to list all CSS rules that affect a chosen element and determine if a width:;
or height:;
value has been assigned already in CSS before calculating the aspect ratio.
In thinking through how it should work, here's what I came up with:
Width |
Height |
Aspect-Ratio |
Calculated |
|
|
✓ |
height |
✓ |
|
✓ |
height |
|
✓ |
✓ |
width |
✓ |
✓ |
✓ |
nothing |
✓ |
✓ |
✓ with !important |
nothing |
This means any time there is both a width
and height
applied to the element in CSS, it would always take those values over the implied aspect-ratio
, even if that aspect-ratio
was marked !important
.
For extracting values from formatted CSS. I have the following regex which will look for rules that contain -eq-aspect-ratio
with the following syntax:
aspect ratio property
= property name
: width
/ height
property name
= -eq-aspect-ratio
width
= number with optional decimal and optional trailing digits
height
= number with optional decimal and optional trailing digits
So here's the regex that will extract this and give us: a CSS selector, the width value, the height value:
/^(.*){.*-eq-aspect-ratio:\s*(\d*\.?\d+)\/(\d*\.?\d+)/gm
And here's my test with formatted CSS using one rule per line and some other simple transformations JavaScript can apply to any CSS to get it ready for extraction: https://regex101.com/r/kSMEeT/1
I wrote an almost working plugin yesterday on the plane - I'm going to keep toying around with it until I can get it working (by checking not the computed styles, but what CSS properties apply to each given element) but it's looking really hopeful and came together a lot faster than I thought it would!
Any thoughts on the precedence I have set in the table above?
Any comments on the prefix I have chosen for development -eq-aspect-ratio
?
Any ideas about how such a plugin should be structured?
I'll post my polyfill here once I get it working!