Using an Element’s Aspect Ratio

All elements in HTML are represented by boxes, which means all elements have a width and a height (even if the value of those is zero). Therefore there is always a relationship between the width and height of an element which can be described as its aspect ratio, represented by aspect ratio = width ÷ height.

CSS recognizes that styling based on the current state of the aspect ratio is useful at the level of the document with the Orientation feature, but this is based on the viewport, equal to the aspect ratio of the <html> element and doesn't offer any way to apply styles to any other element based on its own aspect ratio.

Parts Required

JS Tests

Aspect ratio of element as it appears in the browser:

element.offsetWidth / element.offsetHeight

Plugins Capable

Syntax Examples

CSS (for the <html> element only)

@media (min-aspect-ratio: 16/9) {
  body {
    background: lime;
  }
}
@media (max-aspect-ratio: 16/9) {
  body {
    background: hotpink;
  }
}

EQCSS

@element .min-aspect-ratio and (min-aspect-ratio: 16/9) {
  $this {
    background: greenyellow;
    border-color: limegreen;
  }
}

@element .max-aspect-ratio and (max-aspect-ratio: 16/9) {
  $this {
    background: greenyellow;
    border-color: limegreen;
  }
}

Selectory

.min-aspect-ratio[test="this.offsetWidth/this.offsetHeight > 16/9"] {
  background: lime;
}

.max-aspect-ratio[test="this.offsetWidth/this.offsetHeight < 16/9"] {
  background: lime;
}

Demos

Further Reading