WICG / aspect-ratio

This is a repo to explore, and hopefully define a way to maintain aspect ratio
19 stars 8 forks source link

min-aspect-ratio and max-aspect-ratio on elements #5

Open tomhodgins opened 8 years ago

tomhodgins commented 8 years ago

Hi! This weekend I was experimenting with writing element queries based on the aspect ratio of an element. I learned that there is min-aspect-ratio and max-aspect-ratio support on @media queries which does the exact behaviour (and syntax) that I had desired, the only issue is that @media is limited to the browser's aspect ratio, and so these conditions can't be used to style elements based on their own aspect ratio.

I grabbed the source to EQCSS.js from http://elementqueries.com/EQCSS.js and added the following code:

// Min-aspect-ratio
case "min-aspect-ratio":

  var el_width = EQCSS.data[i].conditions[k].value.split('/')[0],
      el_height = EQCSS.data[i].conditions[k].value.split('/')[1];

  if (!(el_width/el_height <= elements[j].offsetWidth/elements[j].offsetHeight)){
    test = false;
    break test_conditions;
  }

break;

// Max-aspect-ratio
case "max-aspect-ratio":

  var el_width = EQCSS.data[i].conditions[k].value.split('/')[0],
      el_height = EQCSS.data[i].conditions[k].value.split('/')[1];

  if (!(elements[j].offsetWidth/elements[j].offsetHeight <= el_width/el_height)){
    test = false;
    break test_conditions;
  }

break;

Now the following syntax will work on @element queries with EQCSS in all browsers IE8 and up:

@element "div" and (min-aspect-ratio: 16/9) {
  $this {
    background: red;
  }
}
@element "div" and (max-aspect-ratio: 16/9) {
  $this {
    background: lime;
  }
}

And here is an extreme example, what I had in mind when I was looking for support, showing how different container queries could be written to allow a layout to recognize the aspect ratio it has and apply styles to many elements when that condition is met:

I think if would be really cool if this sort of thing was in CSS!